1

I have several jQuery functions on my website but not on every page all of them are required. All of them are exectued from one XXX.js file for example:

jQuery(function() {
$(".title").slug({
    slug:'slug',
    hide: false
});         });

and if any of the elements is missing the rest of the functions are not executed. How to execute for example this function only if the element exists?

1

6 Answers 6

2

The real answer is that the .slug() jQuery plug-in is quite poorly written. It's something like 20 lines of code and it's full of mistakes.

The proper place to fix this issue in in that plugin so it only has to be done once, not everywhere you use it. I would suggest changing that plug-in to this code which fixed a bunch of issues:

//
//    jQuery Slug Generation Plugin by Perry Trinier ([email protected])
//  Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html

jQuery.fn.slug = function(options) {
    var settings = {
        slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready() 
        hide: true     // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span. 
    };

    // merge options and settings
    if(options) {
        jQuery.extend(settings, options);
    }

    // save jQuery object for later use in callback
    if (this.length > 0) {
        var self$ = this.eq(0);

        jQuery(document).ready( function() {
            if (settings.hide) {
                jQuery('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
                jQuery('input.' + settings.slug).hide();
            }
            self$.keyup(function() {
                var slugcontent = jQuery(this).val();
                var slugcontent_fixed = slugcontent.replace(/\s/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
                jQuery('input.' + settings.slug).val(slugcontent_fixed);
                jQuery('span.' + settings.slug).text(slugcontent_fixed);
            });
        });
    }

    // return our jQuery object so it's chainable
    return this;
};

This change fixes these issues with the prior code:

  1. It will now work properly if you call it on an empty jQuery object
  2. It will now work properly if called before the document is ready
  3. It is no longer making unnecessary calls to turn things into jQuery objects that are already jQuery objects
  4. If called on a selector with more than one object in it, it will only operate on the first item in the selector to prevent the problems that could occur otherwise
  5. Made the keyup callback an anonymous function rather than creating a new variable.

Note: This plug-in is written to only work with one slug field per page. As such, you should probably be using it with an id value like "#title" rather than a class name like ".title" because the id will never return more than one field and never get you into trouble that way.

I've verified that this code works here: http://jsfiddle.net/jfriend00/CJJGz/.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This is exactly the kind of example code I was looking for when writing my plugin.
1

You could add an if before the code is called -

if ($(".title").length)

1 Comment

the check for greater than 0 is redundant, you just need to check it has length not that the length is greater than 0
1

You can test the length of the returned jQuery object, if it has a length of zero, the selector was not matched and the element was not found, e.g:

if ($(".title").length) {
    $(".title").slug({
        slug:'slug',
        hide: false
    }); 
}

Comments

1

You can check if the element exist by check its size:

if ($(selector).length) {
// Do what you want
}

Comments

0

You could check if the element exists like this:

 jQuery(function() {
   if($('.title').length != 0) { 
   $(".title").slug({
      slug:'slug',
      hide: false
    });
    }
 });

4 Comments

Wouldn't it be better to fix this issue in the plug-in itself (which is only 20 lines of code) rather than have to code this upon every use and be evaluating the selector multiple times?
You don't need to check the length is a particular value, just that it has length at all
Yes, totally agree with you. If I had the same problem I would try fixing the plugin code itself.
I don't know why you were downvoted (I didn't do it), but I provided a fixed version of the plug-in (in my answer below) that handles the zero length in the plug-in itself.
0

You can test for the existence of the elements you're working on and if they exist perform the action/function:

if ($('.title').length){
    $(".title").slug({
        slug:'slug',
        hide: false
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.