Attaching jQuery plugin calls to dynamically loaded elements via jQuery,on()

Asked
Active3 hr before
Viewed126 times

10 Answers

loadedjqueryplugin
90%

5 The simplest thing to do is to just explicitly apply the plugin(s) in the "success" handler(s) of your ajax calls. – Pointy Dec 31 '11 at 21:52 , The plugin probably uses $(you_passed_selector).hover() as its hook, you can just change the plugin to use $(document).on('hover', you_passed_selector, function() {});. Or like previously stated easiest way to to bind on new elements when added. – Chad Dec 31 '11 at 23:57 ,What is the correct approach to applying a plugin to elements loaded after the initial $(document).ready()?,I have used the jQuery Livequery plugin in the past to do this

If any other element changes, it must be because of javascript, hence you can call functions after created new content.

$(".child", parentElementContext).hoverIntent(makeTall, makeShort)

1) What i typically do is create an init method that takes a context (such as the document).

MyPage.init = function(context) {
   $('.selector', context).hoverIntent();
   $('.other', context).dialog(); // any other plugins
};

Then I manually call init when I update the DOM (because i dont always need to call init when I update the dom)

$.ajax({
   url: url,
   data: data,
   success: function(data) {
      var context = $('.parent');
      context.html(data);
      MyPage.init(context); //calls hoverIntent and other plugins
   }
});
load more v
88%

Sponsored by and others.

$.jnotify(message, [options]);
72%

Once the web page is being fully loaded, then the same event handler is not being attached to newly created elements.,It seems like the event handler is being attached conceptually.,You can use any of the above-specified ways on your webpage to attach the event on the dynamically created element.,When you perform some action on new elements, then the event bind with it not trigger on the new element. But it is working on the elements which are created during the webpage loading.

Append a new <li> to the <ul> element on the add button click and also attaching click event on <li> using .on() method.

<input type='button' value='Add' id='but_add'>
<ul id='lists'>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ul>

<!-- Script -->
<script type="text/javascript">
$(document).ready(function(){

 // Click on list item
 $('#lists li').click(function(){
    $('#lists li').css('background','#ffffff');
    $(this).css('background','#d9f531');
 });

 // Add new list item 
 $('#but_add').click(function(){

   // Attaching click event on new list item
   $('#lists').append('<li>New List item</li>').on('click','li',function(){
     $('#lists li').css('background','#ffffff');
     $(this).css('background','#d9f531');
   });
 });
  
});
</script>
load more v
65%

First, let’s take a look at the issue with jQuery .on(). The following jQuery code attaches a click event to all div elements present on the page and when clicked, it logs the text in the browser console:,And to attach click event to span element, we can use any of these codes:,This works great for all the div elements present on the page at the time of attaching the event. But the moment a div element is added dynamically (via code), the click event will not work. Consider the following jQuery code:,In fact, for following jQuery code .on() works for even dynamically added elements. As here, before the event is attached, the dynamic div is already appended to the HTML body:

First, let’s take a look at the issue with jQuery .on(). The following jQuery code attaches a click event to all div elements present on the page and when clicked, it logs the text in the browser console:

$(document).ready(function() {
   $('div').on('click', function() {
      console.log("Clicked.");
   });
});
load more v
75%

$('body').on('click', selector, function() {
   // do something
});
load more v
40%

Now, let’s create a dynamic element, attach it to our parent element (that is main <div>) and finally attach a click event to it using the .on() method.,I would create a <span> element in my script, and add the element to the <div>. Next, I’ll use the .on() method to add an event (click in our case) to the <span>, which is a descendant (child) of the <div> element.,Any <span> element that we add to the <div> now has a click event attached to it. In the above example, I have used the span keyword as childSelector to the .on() method. See the syntax above.,Let me first explain how you can use the .click() method to trigger the click event. I have a <div> element on my web page and I can easily bind the click event to it. Although, we often use the <div> as a container, we can add an event to it.

<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div id="divMain"> Click Me </div>
</body>

<script>
    $(document).ready(function () {
        // Bind the DIV element to the .click() method.
        $('#divMain').click(function () {
            alert('Success');
        });
    });
</script>
</html>
load more v
22%

Bring Bootstrap's components to life with over a dozen custom jQuery plugins. Easily include them all, or one by one.,Bootstrap's alert plugin exposes a few events for hooking into alert functionality.,Bootstrap's affix plugin exposes a few events for hooking into affix functionality.,Bootstrap's collapse class exposes a few events for hooking into collapse functionality.

$(document).off('.data-api')
load more v
60%

If you are adhering to the “scripts at the bottom” best practice, then you have no need for jQuery’s document ready function as the HTML is already loaded by the time the script is run.,$(function() {}); is the same as document ready. Notice that you are invoking the jQuery function constructor and passing a function callback as opposed to a selector, like you normally do.,I am interested in the “scripts at bottom” vs jQuery “on document ready” strategy, but I was puzzled to note that this page loads all its own scripts in the HEAD section. Perhaps this has to do with its blogging setup?,Robb, actually that is not a shortcut for document ready. That is a self-executing anonymous function. It just scopes the variable jQuery as the $ symbol. This would allow you to safely use another library that overwrites the value of the $ variable.

If you are adhering to the “scripts at the bottom” best practice, then you have no need for jQuery’s document ready function as the HTML is already loaded by the time the script is run.

<p id="zack">This element is on the page <strong>BEFORE</strong> all the scripts. No document ready needed.</p>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script type="text/javascript" charset="utf-8">

    // if you include your scripts at the very bottom, you don't need document ready
    (function($) {

      $("#zack").css("color", "green");
      $("#slator").css("color", "red");

    }(jQuery));

  </script>

<p id="slater">This element comes after the scripts and won't be available.</p>
load more v
48%

JQuery is a cross-browser lightweight JavaScript library. In simple words jQuery has been designed to make navigation to any element easier, or adding/invoking event handlers on your HTML page and also simplify the way you access the elements in your web pages, provide help in working with client-side events, enable visual effects like animation, and make it easier to use Ajax in your applications.,Chaining reduces the code segment and keeps it very clean and easy to understand. Generally chaining uses the jQuery built in functions that makes compilation a bit faster.,We can use interactions for basic mouse-based behaviours to any element. Examples of Interactions are the following:,By default, the datepicker calendar opens in a small overlay when the associated text field gains focus. For an inline calendar, simply attach the datepicker to a div or span.

<script src="http: //ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"></script> 
load more v
23%

Adding the jQuery Accordion Widget to the Project,Adding the jQuery Library to the Project,jQuery Accordion Widget,jQuery works by connecting dynamically-applied JavaScript attributes and behaviors to elements of the DOM (Document Object Model). Let’s add an element to the DOM and try to affect its properties. We’ll create a heading that changes color from black to blue when we click on it.

<html>

<head>
   <title>*jQuery Test Project*</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   *<style type="text/css">

   </style>*
</head>

<body>
   TODO write content
</body>

</html>
load more v

Other "loaded-jquery" queries related to "Attaching jQuery plugin calls to dynamically loaded elements via jQuery,on()"