...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
February 28, 2012

how to get keycode value without passing event in JS for firefox?

Question by sadique

I have a JSP page which has an event onkeydown and calla a Ajax function ajaxFn(this), this function calls a series of functions and then comes to common function ajaxInteraction(response,ajaxObj).
In this common function there is a subfunction which determines the keycode value,

ajaxObj.onkeydown = function(){

var keynum;
//  keynum = event.which;

if(window.event) // IE
{
    keynum = event.keyCode;
}

which recognises only the value from IE and does not recognises Mozilla.
I want to capture the keycode values in the same function for mozilla.
Am not able to capture the value using event.which since event is not passed here from JSP.

P.S: i cannot change the existing code.

Answer by Starx

Events are the only method through which you will able read user’s interaction.

There is no other way to do this, than to use events.

For Firefox use event.charCode

var code = event.charCode ? event.charCode : event.keyCode;
Read more

How do I add new items to a cart and iterate through them to display using php?

Question by sharataka

I am trying to pass data from a product page into a shopping cart page using an array. There are multiple attributes that the viewcart.php will receive from the previous page (price, link, title, and retailer). I’d like to save them all using an array. For each additional item a customer adds to the shopping cart, I’m trying to get a counter variable ($i) to increment an array $_SESSION[‘cart’][$i][‘attribute’]. How do I do this?

I’m not sure this is the right way to add new products to the cart. In the end, I’d like a way to be able to display all the products in the cart using a for loop. This is the start I have so far on the shopping cart script:

<?php

  // The shopping cart needs sessions, so start one
  session_start();

  @$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];


  if($link) {
    //new item selected
    if(!isset($_SESSION['cart'])) {
      $_SESSION['cart'] = array();
      $_SESSION['items'] = 0;
      $_SESSION['total_price'] ='0.00';
    }

    if(isset($_SESSION['cart'][$link])) {
      $_SESSION['cart'][$link]++;
    } else {
      $_SESSION['cart'][$link] = 1;
    }


  }

  if(($_SESSION['cart']) && (array_count_values($_SESSION['cart']))) {
    echo " in your cart and we're working to display them";
  } 
  else {
    echo "<p>There are no items in your cart</p><hr/>";
  }

?>

This is the for loop that I’m thinking I could use. I’m looking for some way to display all the items in the array.

for ($x=0; $x<=$i; $i++)
  {
  echo "The price is " . $_SESSION['cart'][$x][price] . "  Retailer is " . $_SESSION['cart'][$x]    [retailer] . "<br>";
  }

Answer by Faraz

The easiest way to do this is by creating a temp_cart table in your database.. in which you should store the items that user adds to their cart.. Then on checkout page.. you can simply display them using select query. In that way.. it will be easier for you to allow the user to edit their cart on viewcart.php page.

Answer by Starx

I don’t like the way you are doing this. Session management is very simple for shopping carts. Keep your session as lite as possible. Storing price in the session is very bad way, as it can be easily manipulated.

Here is a simple example of what you can use.

if(isset($_SESSION['items'][$_GET['item_id']])) {
    $_SESSION['items'][$_GET['item_id']]++; //add one to the total count
} else {
    $_SESSION['items'][$_GET['item_id']] = 1; //If added for the first time
}

Now process it

foreach($_SESSION['items'] as $id => $count) {
     echo $id; // product id
     echo $count; // product count
}

P.S: Remember to sanitize the input. I have omitted that

Read more

how to change background img size

Question by SooIn Nam

   $(this).css('background','url(img/49057_584817416_4750_q.jpg) no-repeat 10% 40%,url(img/yes_no.png) no-repeat 50% 80%,url(../img/invitation.png)');

I only want to resize img/49057_584817416_4750_q.jpg

Any Thought?
Thank you.

Answer by Starx

Through CSS3, you can do something like this

-webkit-background-size: 80% 80%; /* Saf3-4 */
     -moz-background-size: 80% 80%; /* FF3.6 */
          background-size: 80% 80%; /* Opera, IE9, Saf5, Chrome, FF4 */
Read more

Load StyleSheet dynamically with Callback function

Question by Mahan

I have this short JavaScript function that loads CSS file dynamically. But im not yet good at JavaScript so can anyone give me an idea on how can I create a callback function once the CSS file was successfully loaded…

function loadStyleSheet(url){
    if(document.createStyleSheet) {
        try {document.createStyleSheet(url);} catch (e) { }
    }
    else{
        var css;
        css         = document.createElement('link');
        css.rel     = 'stylesheet';
        css.type    = 'text/css';
        css.media   = "all";
        css.href    = url;
        document.getElementsByTagName("head")[0].appendChild(css);
    }
}

P.S. If you have an idea on how I can also know if the loading of CSS file has failed. Well i will thank you more ^_^

Answer by Starx

I think the simplest would be to append the markup to the head on load

$('<link rel="stylesheet" href="link.css" type="text/css" />').appendTo("head")
.each(function() { //little trick to create the callback fucntion
    // I am the callback
});

P.S: Its a jQuery solution. I didn’t notice JS & CSS tag, but still its a good solution

Read more

Background smaller than containing div (of variable size)

Question by danapaige

I want to create a slightly indented background behind embedded media, for which the size varies. It should look like this:

what it should look like

See how the green background is slightly indented from the top and bottom of the youtube video? I have gotten everything else to show up as I want, I just can’t figure out how to position the background slightly inside of the embedded media item. Especially since I know the media item size will change.

You can see what I have so far on JSfiddle.

Answer by Starx

Simple give negative margin like

iframe { margin-top: -10px; }

DEMO

Read more

Toggling a div with JQuery and having link text switch

Question by joeschmidt

I have some code where you click on a link and jQuery opens a div. In its normal state the link says “Watch Video”, I’d like to have it work so that when the div becomes visible the link text changes to “Close video”. Clicking on the close video link closes the div.

Here is an example of what I’m trying to do: http://jsfiddle.net/XsvG9/

Here’s the actual code:

JS

$("span.trigger a").click(function() {
    the_id = $(this).attr('id');

$("#toggle_container-"+the_id).slideToggle(500, function() {
    $("span.trigger a"+the_id).text($(this).is(':visible') ? 'Close video' : 'Watch video');
    });
});

HTML

<p class="data">Posted Feb 20 | <a href="/supersecret/jsmith/post/399/">0 comments</a> |<span id="votes_count399" class="votes_count"> 0 </span>

<span id="vote_buttons399" class="vote_buttons">faves<a id="399" title="Favorite This" class="vote_up" href="javascript:;">#</a></span> | <span class="trigger"><a id="399" href="javascript:;">Watch video</a></span>
</p>

<div class="hide" id="toggle_container-399" style="display: none;">
    <iframe width="555" height="315" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/z1c1OIMbmb0"/></div>
</div>

I have it working where the div toggles open, but the link does not switch text. I’ve been staring at this too long, so I would appreciate it if a fresh pair of eyes could help find the error in my ways.

Thanks for your help.

Answer by Starx

Your anchors have same id 399 which is what is creating the main problem.

Instead of .text() method, use .html() to change the text as well.

This demo removes all the problem and works perfectly.

Read more

set cookie then redirect to another domain

Question by mulllhausen

i’m not sure if i’m doing something wrong in my code or if my desired action is just not allowed in the standards…i’m trying to set a cookie on my localhost then redirect the user off to another domain. (for some background on why i would want to do this: as part of the oauth 1.0 signin process i want to set the oauth state then redirect the user off to the service provider to signin; but this is not really relevant to my question – it just may be useful in case someone wants to suggest a better way to do what i am trying to do…)

here is a simpified version of the relevant piece of my php code:

setcookie('oauth_state', 'one', time() + 60*60, '/', 'localhost', false, false);
header("Location: http://google.com/");
exit;

i’m testing on firefox 10.0.2 on ubuntu and no cookie at localhost is being set. what am i doing wrong?

Answer by jjs9534

Cookies are domain specific. So if you set the cookie in one domain and then redirect to a new domain, then the cookie you previously set will not be visible.

Answer by Starx

The time is set to 3600 which is prehistoric.

Change this to time()+3600 it will work.

Read more
February 27, 2012

The right place for running a jQuery

Question by Constantin.FF

Adding different plugins, scripts and other jquery the code gets pretty messy.
What is the right place for running each jquery, and does it need separated functions for each element.

Some of the scripts are runs like this in the head of the page:

$(function(){ ...

jQuery(function() { ...

and other need to be at the end:

$( ".add" ).button({ ...

is it wrong to merge all of the functions into one $(function(){ ... ?

Answer by Starx

There is NO hard-n-fast rule for where to put a jQuery snippet.

You put it at correct place where it is needed.

  • $(function(){ is short for $(document).ready(function() {. It is an event, which executes when the document is ready for processing.

  • $( ".add" ).button({ is assigning a plugin(probably) to an selector. Every plugins have their own event triggers and they will occur either automatically or manually like through, hovers and clicks

You should put(always) code at the correct event triggers/function call for them to function properly.

But

If you are using too many scripts on your page, that it is slowing the load time. Then they are better when they are placed right before the </body>


References

Read jQuery Events Documentation [docs here] very clearly to understand, where to put your code effectively

Read more
...

Please fill the form - I will response as fast as I can!