views:

38

answers:

2

I'm new to jQuery and Javascript. I'm trying to make a button that I can double click which then loops through all elements in the webpage with a certain class and fades them.

Currently, I'm trying this:

$(".fadeall").dblclick(function() {
    $("div.section").each(function(idx,item) {
        item.fadeTo(25,inactiveOpacity);
    });
});

In my debugger I see the double click happening, but the function in the each call is not being triggered.

I'm believe I'm not matching the div.section elements correctly, but don't know the correct approach.

+4  A: 

It should be erroring out since the DOM element doesn't have a .fadeTo() function, you need to wrap the element you're looping over (item) in a jQuery object, like this:

$(item).fadeTo(25,inactiveOpacity);

Or, this works as well, for example:

$(".fadeall").dblclick(function() {
  $("div.section").each(function() {
    $(this).fadeTo(25,inactiveOpacity);
  });
});
Nick Craver
+2  A: 

Assuming the HTML has <div> elements with the class section, the only other thing I can see that you would need to do is wrap item in a jQuery object.

$(".fadeall").dblclick(function() {
    $("div.section").each(function(idx,item) {
           // Wrapped "item" so you have access to jQuery methods
        $(item).fadeTo(25,inactiveOpacity);
    });
});

Since item is the DOM element, it needs to be wrapped with a jQuery object so that it will have access to methods like .fadeTo().

Another approach is to use this in the .each(), which will refer to the DOM element as well.

$(".fadeall").dblclick(function() {
    $("div.section").each(function() {
           // Wrapped "this" so you have access to jQuery methods
        $(this).fadeTo(25,inactiveOpacity);
    });
});

EDIT:

Also, make sure the DOM is loaded before your code runs:

   // Wrapping code like this ensures that the DOM elements will be
   //    loaded before your code runs.
$(function() {
    $(".fadeall").dblclick(function() {
        $("div.section").each(function() {
               // Wrapped "this" so you have access to jQuery methods
            $(this).fadeTo(25,inactiveOpacity);
        });
    });
});

This is a shortcut for jQuery's .ready() method, which will ensure that your code doesn't run until the elements are available.

patrick dw