DA.
DA.

Reputation: 40697

jquery trigger event on match of element on page load

I've created a custom jQuery function and I want to call it for every match of an element on the page when it loads. The syntax I'm using to call the function:

$(document).ready(function() {
    $("div.class1.class2").fixClassesForIE6("a","b");
}); 

That syntax does nothing. The fixClassesForIE6 function is never called.

I think I maybe need to use 'trigger' in some form? But I'm not entirely sure.

Ultimately, I want:

  1. the page to load
  2. find all DIV elements on the page with class1 and class2
  3. Trigger my function for each match

Upvotes: 0

Views: 1151

Answers (3)

Roatin Marth
Roatin Marth

Reputation: 24115

Define fixClassesForIE6 using the plugin syntax, and all should be good:

(function($) {
    $.fn.extend({
        fixClassesForIE6: function() {
            return this.each(function() {
                // plugin logic goes here
            })
        }
    })
}(jQuery);

If you've done that and it's not working, then you've got problematic code elsewhere.

Upvotes: 0

Matt
Matt

Reputation: 41842

I can see 2 possible problems:

1) Your selector is wrong. You can confirm this by executing your selector, by itself, in a JavaScript debugger, such as FireBug for Firefox.

2) The method fixClassesForIE6() ... is that your method? I do not recognize it as a JQuery method. If it is your method, then this will not work - because you are calling it on the results of the selector, which don't have that method. Instead, try something like:

$(document).ready(function() { 
    var elements = $("div.class1.class2");
    elements.each(function(){ fixClassesForIE6(this, "a","b"); });
} 

Upvotes: 1

devpl
devpl

Reputation: 204

For selecting all DIV elements on the page with class1 and class2, I think that you should use $("div.class1,div.class2") instead.

For doing something for each matching div w/ class1 or class 2, i think that you can use the each() function here?

$("div.class1,div.class2").each(
     function(index){
       //do something here
     });

Upvotes: 0

Related Questions