tags:

views:

29

answers:

2

Hi all,

Im stuck on some jquery, and I dont know why it isnt working...

$('img').click(function() {
    $('img').removeClass('bob');
    $(this).addClass('bob');
});

var test = $('img.bob').attr('src');
$('div.button').click(function() {
    alert(test);
});

basically i need to get the attr ID of the image selected, but the alert only returns 'null'.

Any suggestions would be greatly appreciated. Im pulling my hair out...

A.

A: 

try this:

$('div.button').click(function() {
    alert(this.id.ToString());
});
Hogan
+1  A: 

Remember that the click event you assigned does not run until you actually click an <img>, so trying to get an image with the class .bob before any click events have occurred on the <img> elements will result in 0 elements matched (unless you have .bob assigned to one of the <img> elements before the page loads.

You need to retrieve the 'id' inside the button's click handler.

Also, you can make your code a little more efficient by caching the <img> elements found (as long as you're not adding additional ones dynamically after the page loads).

var $img = $('img').click(function() {
    $img.not(this).removeClass('bob');
    $(this).addClass('bob');
});

$('div.button').click(function() {
    var test = $img.filter('.bob').attr('id');
    alert(test);
});

If you are going to be adding images dynamically, then you don't need to cache them.

$('img').click(function() {
    $('img').not(this).removeClass('bob');
    $(this).addClass('bob');
});

$('div.button').click(function() {
    var test = $('img.bob').attr('id');
    alert(test);
});
patrick dw