EzDevInfo.com

jquery-plugins interview questions

Top jquery-plugins frequently asked interview questions

jQuery Scroll To bottom of the page

after my page is done loading. I want jQUery to nicely scroll to the bottom of the page, animating quickly, not a snap/jolt.

do i need a plugin like ScrollTo for that? or is that built into jQuery some how?


Source: (StackOverflow)

Change Placeholder Text using jQuery

I am using a jQuery placeholder plugin(https://github.com/danielstocks/jQuery-Placeholder). I need to change the placeholder text with the change in dropdown menu. But it is not changing. Here is the code:

$(function () {
    $('input[placeholder], textarea[placeholder]').placeholder();
    $('#serMemdd').change(function () {
        var k = $(this).val();
        if (k == 1) {
            $("#serMemtb").attr("placeholder", "Type a name (Lastname, Firstname)").placeholder();
        }
        else if (k == 2) {
            $("#serMemtb").attr("placeholder", "Type an ID").placeholder();
        }
        else if (k == 3) {
            $("#serMemtb").attr("placeholder", "Type a Location").placeholder();
        }
    });
});

My Html:

<div class="filterbox">
        <select name="ddselect" id="serMemdd">
            <option value="1" selected="selected">Search by Name</option>
            <option value="2">Search by ID</option>
            <option value="3">Search by Location</option>
        </select>
        <input id="serMemtb" type="text" style="width: 490px" placeholder="Type a name    (Lastname, Firstname)" />
        <input id="seMemBut" type="button" value="Search" />
    </div>

Can anyone figure this out?


Source: (StackOverflow)

Advertisements

jQuery plugin template - best practice, convention, performance and memory impact

I've started to write few jQuery plugins and figured it'd be nice to setup my IDE with a jQuery plugin template.

I have been reading some articles and posts on this site related to plugin convention, design, etc.. and thought I'd try and consolidate all of that.

Below is my template, I am looking to use it frequently so was keen to ensure it generally conforms to jQuery plugin design convention and whether the idea of having multiple internal methods (or even its general design) would impact performance and be prone to memory issues.

(function($)
{
    var PLUGIN_NAME = "myPlugin"; // TODO: Plugin name goes here.
    var DEFAULT_OPTIONS =
    {
        // TODO: Default options for plugin.
    };
    var pluginInstanceIdCount = 0;

    var I = function(/*HTMLElement*/ element)
    {
        return new Internal(element);
    };

    var Internal = function(/*HTMLElement*/ element)
    {
        this.$elem = $(element);
        this.elem = element;
        this.data = this.getData();

        // Shorthand accessors to data entries:
        this.id = this.data.id;
        this.options = this.data.options;
    };

    /**
     * Initialises the plugin.
     */
    Internal.prototype.init = function(/*Object*/ customOptions)
    {
        var data = this.getData();

        if (!data.initialised)
        {
            data.initialised = true;
            data.options = $.extend(DEFAULT_OPTIONS, customOptions);

            // TODO: Set default data plugin variables.
            // TODO: Call custom internal methods to intialise your plugin.
        }
    };

    /**
     * Returns the data for relevant for this plugin
     * while also setting the ID for this plugin instance
     * if this is a new instance.
     */
    Internal.prototype.getData = function()
    {
        if (!this.$elem.data(PLUGIN_NAME))
        {
            this.$elem.data(PLUGIN_NAME, {
                id : pluginInstanceIdCount++,
                initialised : false
            });
        }

        return this.$elem.data(PLUGIN_NAME);
    };

    // TODO: Add additional internal methods here, e.g. Internal.prototype.<myPrivMethod> = function(){...}

    /**
     * Returns the event namespace for this widget.
     * The returned namespace is unique for this widget
     * since it could bind listeners to other elements
     * on the page or the window.
     */
    Internal.prototype.getEventNs = function(/*boolean*/ includeDot)
    {
        return (includeDot !== false ? "." : "") + PLUGIN_NAME + "_" + this.id;
    };

    /**
     * Removes all event listeners, data and
     * HTML elements automatically created.
     */
    Internal.prototype.destroy = function()
    {
        this.$elem.unbind(this.getEventNs());
        this.$elem.removeData(PLUGIN_NAME);

        // TODO: Unbind listeners attached to other elements of the page and window.
    };

    var publicMethods =
    {
        init : function(/*Object*/ customOptions)
        {
            return this.each(function()
            {
                I(this).init(customOptions);
            });
        },

        destroy : function()
        {
            return this.each(function()
            {
                I(this).destroy();
            });
        }

        // TODO: Add additional public methods here.
    };

    $.fn[PLUGIN_NAME] = function(/*String|Object*/ methodOrOptions)
    {
        if (!methodOrOptions || typeof methodOrOptions == "object")
        {
            return publicMethods.init.call(this, methodOrOptions);
        }
        else if (publicMethods[methodOrOptions])
        {
            var args = Array.prototype.slice.call(arguments, 1);

            return publicMethods[methodOrOptions].apply(this, args);
        }
        else
        {
            $.error("Method '" + methodOrOptions + "' doesn't exist for " + PLUGIN_NAME + " plugin");
        }
    };
})(jQuery);

Thanks in advance.


Source: (StackOverflow)

Making custom right-click context menus for my web-app

I've a few websites like google-docs and map-quest that have custom drop down menus when you right-click. Somehow they override the browser's behavior of drop-down menu, and I'm now sure exactly how they do it. I found a jQuery plugin that does this, but I'm still curious about a few things:

  • How does this work? Is the browser's drop-down menu actually being overridden, or is the effect just simulated? If so, how?
  • What does the plugin abstract away? What's going on behind the scenes?
  • Is this the only way of achieving this effect?

custom context menu image

See several custom-context menus in action


Source: (StackOverflow)

Can someone explain how to implement the jQuery File Upload plugin?

EDIT:

This still seems to be getting traffic so I'll explain what I ended up doing. I eventually got the plugin working by following Subrat's tutorial, which is the accepted answer. However, jQuery File Upload is a real hassle and if you're looking for a simple file upload plugin, I would highly recommend Uploadify (thanks CORSAIR!). As an answer pointed out, it is only free for non-commercial use.

Background

I'm trying to use blueimp's jQuery File Upload to allow users to upload files. Out of the box it works perfectly, following the setup instructions. But to actually use it practically on my website, I want to be able to do a couple things:

  • Include the uploader on any of my existing pages
  • Change the directory for uploaded files

All the files for the plugin are located in a folder under the root.

I've tried...

  • Moving the demo page into the root and updating the paths for the necessary scripts
  • Changing the 'upload_dir' and 'upload_url' options in the UploadHandler.php file as suggested here.
  • Changing the url in the second line of the demo javascript

In all cases the preview shows and the progress bar runs, but the files fails to upload and I get this error in the console: Uncaught TypeError: Cannot read property 'files' of undefined. I don't understand how all the parts of the plugin work which is making it difficult to debug.

Code

The javascript in the demo page:

$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = 'file_upload/server/php/UploadHandler.php',
    uploadButton = $('<button/>')
        .addClass('btn')
        .prop('disabled', true)
        .text('Processing...')
        .on('click', function () {
            var $this = $(this),
                data = $this.data();
            $this
                .off('click')
                .text('Abort')
                .on('click', function () {
                    $this.remove();
                    data.abort();
                });
            data.submit().always(function () {
                $this.remove();
            });
        });
$('#fileupload').fileupload({
    url: url,
    dataType: 'json',
    autoUpload: false,
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
    maxFileSize: 5000000, // 5 MB
    // Enable image resizing, except for Android and Opera,
    // which actually support image resizing, but fail to
    // send Blob objects via XHR requests:
    disableImageResize: /Android(?!.*Chrome)|Opera/
        .test(window.navigator.userAgent),
    previewMaxWidth: 100,
    previewMaxHeight: 100,
    previewCrop: true
}).on('fileuploadadd', function (e, data) {
    data.context = $('<div/>').appendTo('#files');
    $.each(data.files, function (index, file) {
        var node = $('<p/>')
                .append($('<span/>').text(file.name));
        if (!index) {
            node
                .append('<br>')
                .append(uploadButton.clone(true).data(data));
        }
        node.appendTo(data.context);
    });
}).on('fileuploadprocessalways', function (e, data) {
    var index = data.index,
        file = data.files[index],
        node = $(data.context.children()[index]);
    if (file.preview) {
        node
            .prepend('<br>')
            .prepend(file.preview);
    }
    if (file.error) {
        node
            .append('<br>')
            .append(file.error);
    }
    if (index + 1 === data.files.length) {
        data.context.find('button')
            .text('Upload')
            .prop('disabled', !!data.files.error);
    }
}).on('fileuploadprogressall', function (e, data) {
    var progress = parseInt(data.loaded / data.total * 100, 10);
    $('#progress .bar').css(
        'width',
        progress + '%'
    );
}).on('fileuploaddone', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var link = $('<a>')
            .attr('target', '_blank')
            .prop('href', file.url);
        $(data.context.children()[index])
            .wrap(link);
    });
}).on('fileuploadfail', function (e, data) {
    $.each(data.result.files, function (index, file) {
        var error = $('<span/>').text(file.error);
        $(data.context.children()[index])
            .append('<br>')
            .append(error);
    });
}).prop('disabled', !$.support.fileInput)
    .parent().addClass($.support.fileInput ? undefined : 'disabled');
});


I'm surprised by the lack of documentation, it seems like it should be a simple thing to change. I would really appreciate if someone could explain how to do this.


Source: (StackOverflow)

jQuery UI Autocomplete widget search configuration

I'm looking into using the jQuery UI autocomplete widget to implement user lookup by first or last name. It looks like by default autocomplete looks up words by character sequence no matter its occurrence in a word. So if you have data such as: javascript, asp, haskell and you type in 'as' you will get all three. I would like it to at least match beginning of the word. So in above example you get only 'asp'. Is there a way to configure the autocomplete widget to do this?

Ultimately it would be even better to match by beginning of first or last name like it is in Gmail.

Note: I'm trying to figure out a way to do this using the jQuery UI widget specifically. Since I'm already using jQuery UI in my project, I'm planning to stick with it and try not adding additional libraries to my web application.


Source: (StackOverflow)

Facebook style JQuery autocomplete plugin [closed]

Im after a plugin to do autocomplete like facebook does in that you can select multiple items - similar to how tagging a stackoverflow question works.

Here are a couple I ran into:

Have you tried any of these? Were they easy to implement and customize?


Source: (StackOverflow)

Adding a Resource View/Gannt chart to jQuery Fullcalendar

I am using jQuery Fullcalendar and if you're not using it I suggest you do too because it is absolutely fantastic at what it does!

However to be really useful to me and my project (and many others) I honestly believe it needs a resource/gannt view.

Not a problem one would think... until you look under the hood of jQuery FullCalendar and see that the way it generates it's views is not for javascript developer wannabes... ie me.

Having realised this is out of my league I had to go searching elsewhere looking for any calendar/scheduler that will provide a resource view.

Here are three proprietary calendars that promise this feature.

  1. http://java.daypilot.org/
  2. http://www.dhtmlx.com/docs/products/dhtmlxScheduler/index.shtml
  3. http://web2cal.com/ajaxeventscalendar/calendar-demo/912-premium-demo/157-scheduler-view

Unfortunately both daypilot and dhtmlxscheduler lack the clean and clear interface that FullCalendar achieves so well and web2cal just looks and feels unfinished and is still in Beta.

Alternatively I was wondering if anyone has any ideas on how I could integrate a jQuery Gannt chart with jquery fullcalendar.

I have found a few projects that look promising

I have looked into how fullcalendar generates its views and so far have not had any success in extending this to provide a container for one of these gannt charts to 'sit within' fullcalendar and be triggered by its buttons.

This seems to be one of the more popular feature requests with many people asking for it on the official issue tracker

http://code.google.com/p/fullcalendar/issues/detail?id=150&colspec=ID%20Type%20Status%20Milestone%20Summary%20Stars

So I am left at a cross roads. I could pay for a half baked proprietary solution that has minimal to no community support or I can try and find a way of getting a resource view inside of jquery Fullcalendar by asking the people who really know jQuery.

I would happily donate the funds saved from using a proprietary solution to the developer of Fullcalendar.

The developer of FullCalendar seems to have a lot on his plate and I would like to again thank him for this truly amazing calendar.

I hope someone can share a solution with us!

Tim


Source: (StackOverflow)

I'd like to understand the jQuery plugin syntax

The jQuery site lists the basic plugin syntax for jQuery as this:

(function( $ ){    
  $.fn.myPlugin = function() {      
    // there's no need to do $(this) because
    // "this" is already a jquery object

    // $(this) would be the same as $($('#element'));

    this.fadeIn('normal', function(){    
      // the this keyword is a DOM element    
    });    
  };
})( jQuery );

I'd just like to understand what is going on there from Javascript's point of view, because it doesn't look like it follows any syntax I've seen JS do before. So here's my list of questions:

  1. If you replace function($)... with a variable, say "the_function", the syntax looks like this:

     (the_function)( jQuery );
    

    What is "( jQuery );" doing? Are the parenthesis around the_function really necessary? Why are they there? Is there another piece of code you can give that is similar?

  2. It begins with function( $ ). So it's creating a function, that as far as I can tell will never be run, with the parameter of $, which is already defined? What is going on there?

Thanks for the help!


Source: (StackOverflow)

Simple jQuery scroll to anchor up or down the page...?

I'm looking for a way to include a simple slide effect for when you click a link to a local anchor either up or down the page.

If possible i'd like something where you have a link like so:

<a rel='nofollow' href="#nameofdivetc">link text, img etc.</a>

perhaps with a class added so you know you want this link to be a sliding link:

<a rel='nofollow' href="#nameofdivetc" class="sliding-link">link text, img etc.</a>

Then if this link is clicked, the page simply slides up or down to the required place (could be a div, heading, top of page etc).

A bit like I used on this site of mine http://www.adriancrellin.co.uk/ , but this was a good while ago and I'm now doing it for a client and wondered if there are any better or simpler solutions out there.

Any ideas would be great!


This is what I had previously, can't remember where I got the code from exactly now, but it seems to work quite nicely, any better solutions would be great though :o)

    $(document).ready(function(){
    $(".scroll").click(function(event){
        //prevent the default action for the click event
        event.preventDefault();

        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;

        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];

        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;

        //goto that anchor by setting the body scroll top to anchor top
        $('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
    });
});

Source: (StackOverflow)

Pie chart with jQuery [closed]

I want to create a pie chart in JavaScript. On searching I found the Google Charts API. Since we are using jQuery I found that there is jQuery integration for Google Charts available.

But my problem is here the actual data is sent to the Google server for creating the charts. Is there a way to prevent the data from being sent to Google? I am concerned about sending my data to a third party.


Source: (StackOverflow)

jQuery Validate - require at least one field in a group to be filled

I'm using the excellent jQuery Validate Plugin to validate some forms. On one form, I need to ensure that the user fills in at least one of a group of fields. I think I've got a pretty good solution, and wanted to share it. Please suggest any improvements you can think of.

Finding no built-in way to do this, I searched and found Rebecca Murphey's custom validation method, which was very helpful.

I improved this in three ways:

  1. To let you pass in a selector for the group of fields
  2. To let you specify how many of that group must be filled for validation to pass
  3. To show all inputs in the group as passing validation as soon as one of them passes validation. (See shout-out to Nick Craver at end.)

So you can say "at least X inputs that match selector Y must be filled."

The end result, with markup like this:

<input class="productinfo" name="partnumber">
<input class="productinfo" name="description">

...is a group of rules like this:

// Both these inputs input will validate if 
// at least 1 input with class 'productinfo' is filled
partnumber: {
   require_from_group: [1,".productinfo"]
  }
description: {
   require_from_group: [1,".productinfo"]
}

Item #3 assumes that you're adding a class of .checked to your error messages upon successful validation. You can do this as follows, as demonstrated here.

success: function(label) {  
        label.html(" ").addClass("checked"); 
}

As in the demo linked above, I use CSS to give each span.error an X image as its background, unless it has the class .checked, in which case it gets a check mark image.

Here's my code so far:

jQuery.validator.addMethod("require_from_group", function(value, element, options) {
    var numberRequired = options[0];
    var selector = options[1];
    //Look for our selector within the parent form
    var validOrNot = $(selector, element.form).filter(function() {
         // Each field is kept if it has a value
         return $(this).val();
         // Set to true if there are enough, else to false
      }).length >= numberRequired;

    // The elegent part - this element needs to check the others that match the
    // selector, but we don't want to set off a feedback loop where each element
    // has to check each other element. It would be like:
    // Element 1: "I might be valid if you're valid. Are you?"
    // Element 2: "Let's see. I might be valid if YOU'RE valid. Are you?"
    // Element 1: "Let's see. I might be valid if YOU'RE valid. Are you?"
    // ...etc, until we get a "too much recursion" error.
    //
    // So instead we
    //  1) Flag all matching elements as 'currently being validated'
    //  using jQuery's .data()
    //  2) Re-run validation on each of them. Since the others are now
    //     flagged as being in the process, they will skip this section,
    //     and therefore won't turn around and validate everything else
    //  3) Once that's done, we remove the 'currently being validated' flag
    //     from all the elements
    if(!$(element).data('being_validated')) {
    var fields = $(selector, element.form);
    fields.data('being_validated', true);
    // .valid() means "validate using all applicable rules" (which 
    // includes this one)
    fields.valid();
    fields.data('being_validated', false);
    }
    return validOrNot;
    // {0} below is the 0th item in the options field
    }, jQuery.format("Please fill out at least {0} of these fields."));

Hooray!

Shout out

Now for that shout-out - originally, my code just blindly hid the error messages on the other matching fields instead of re-validating them, which meant that if there was another problem (like 'only numbers are allowed and you entered letters'), it got hidden until the user tried to submit. This was because I didn't know how to avoid the feedback loop mentioned in the comments above. I knew there must be a way, so I asked a question, and Nick Craver enlightened me. Thanks, Nick!

Question Solved

This was originally a "let me share this and see if anybody can suggest improvements" kind of question. While I'd still welcome feedback, I think it's pretty complete at this point. (It could be shorter, but I want it to be easy to read and not necessarily concise.) So just enjoy!

Update - now part of jQuery Validation

This was officially added to jQuery Validation on 4/3/2012.


Source: (StackOverflow)

How to launch jQuery Fancybox on page load?

I would like to launch a Fancybox (e.g. Fancybox's version of a modal or light box) on page load. I could bind it to a hidden anchor tag and fire the click event of that anchor tag via JavaScript, but I would rather just launch the Fancybox directly and avoid the extra anchor tag.


Source: (StackOverflow)

CSS rule to apply only if element has BOTH classes

Let's say we have this markup:

<div class="abc"> ... </div>
<div class="xyz"> ... </div>
<div class="abc xyz" style="width: 100px"> ... </div>

Is there a way to select only the <div> which has BOTH abc and xyz classes (the last one) AND override its inline width to make the effective width be 200px?

Something like this:

[selector] {
  width: 200px !important;
}

I am not sure if !important would override inline css also.

Plese note that:

  1. In the real situation I cannot rely on node order of the divs, so "This selector selects the last child" is not the answer.
  2. Likewise, I am not looking for methods which require changing the markup, I know with adding id attributes it would become a non-issue.
  3. In fact there are not 3 <div> elements, there is just one, and it gets changed by a jQueru plugin in response to some state change. If possible, I prefer not to hook to callback functions and piggy-back a function to find when the div has both classes; but that might be a last resort ...

P.S. Apologies for using jQuery tags for better visibility; it is related somehow - but if you feel they have no place at all, feel free to remove them.


Source: (StackOverflow)

JQuery to load Javascript file dynamically

I have a very large javascript file I would like to load only if the user clicks on a certain button. I am using jQuery as my framework. Is there a built-in method or plugin that will help me do this?

Some more detail: I have a "Add Comment" button that should load the TinyMCE javascript file (I've boiled all the TinyMCE stuff down to a single JS file), then call tinyMCE.init(...).

I don't want to load this at the initial page load because not everyone will click "Add Comment".

I understand I can just do:

$("#addComment").click(function(e) { document.write("<script...") });

but is there a better/encapsulated way?


Source: (StackOverflow)