JavaScript Why this click function not working in jquery? [duplicate]

Answer:1

You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;
Answer:2

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))
Answer:3

Try to use .live() instead of .bind(); the .live() will bind .hover to your checkbox after the Ajax request executes.

Answer:4

Event binding on dynamically created elements

Single element:

$(document.body).on('click','.element', function(e) {  });

Child Element:

 $(document.body).on('click','.element *', function(e) {  });

Notice the added *. An event will be triggered for all children of that element.

I have noticed that:

$(document.body).on('click','.#element_id > element', function(e) {  });

It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.

Answer:5

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>
Answer:6

I prefer using the selector and I apply it on the document.

This binds itself on the document and will be applicable to the elements that will be rendered after page load.

For example:

$(document).on("click", $(selector), function() {
    // Your code here
});
Answer:7

Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:

var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}
Answer:8

Take note of "MAIN" class the element is placed, for example,

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

In the above scenario, the MAIN object the jQuery will watch is "container".

Then you will basically have elements names under container such as ul, li, and select:

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });
Answer:9

You can attach event to element when dynamically created using jQuery(html, attributes).

As of jQuery 1.8, any jQuery instance method (a method of jQuery.fn) can be used as a property of the object passed to the second parameter:

function handleDynamicElementEvent(event) {
  console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
    html: $.map(Array(3), function(_, index) {
      return new Option(index, index)
    }),
    on: {
      change: handleDynamicElementEvent
    }
  })
  .appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Answer:10

Try like this way -

$(document).on( 'click', '.click-activity', function () { ... });
Answer:11

you could use

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

or

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

these two methods are equivalent but have a different order of parameters.

see: jQuery Delegate Event

Answer:12

This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.

$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

Note:

wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist. However, selector doesn't necessarily needs to be presented at page loading time. It may come later and the event will bind on selector without fail.

Answer:13

Here is why dynamically created elements do not respond to clicks :

var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
  console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
Answer:14

Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists

$(document).ready(function(){
  //Particular Parent chield click
  $(".buttons").on("click","button",function(){
    alert("Clicked");
  });  
  
  //Dynamic event bind on button class  
  $(document).on("click",".button",function(){
    alert("Dymamic Clicked");
  });
  $("input").addClass("button");  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
  <input type="button" value="1">
  <button>2</button>
  <input type="text">
  <button>3</button>  
  <input type="button" value="5">  
  </div>
<button>6</button>
Answer:15

Bind the event to a parent which already exists:

$(document).on("click", "selector", function() {
    // Your code here
});
Answer:16

Use the .on() method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.

Also as of version 1.9 .live() method is removed.

Answer:17

I prefer to have event listeners deployed in a modular function fashion rather than scripting a document level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.

var iterations = 4;
var button;
var body = document.querySelector("body");

for (var i = 0; i < iterations; i++) {
    button = document.createElement("button");
    button.classList.add("my-button");
    button.appendChild(document.createTextNode(i));
    button.addEventListener("click", myButtonWasClicked);
    body.appendChild(button);
}

function myButtonWasClicked(e) {
    console.log(e.target); //access to this specific button
}
Answer:18

Another flexible solution to create elements and bind events (source)

// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);

Note: This will create an event handler instance for each element (may affect performance when used in loops)

Answer:19
<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>
Answer:20

I have the following JS: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I expect the result to be '', but am instead getting 'a a'. Can anyone explain to me what I am doing wrong? Clarification: What I ...

I have the following JS: "a a a a".replace(/(^|\s)a(\s|$)/g, '$1') I expect the result to be '', but am instead getting 'a a'. Can anyone explain to me what I am doing wrong? Clarification: What I ...

  1. string replace only first instance c#
  2. string replace only first instance java
  3. string replace only first instance javascript
  4. string replace only first instance
  5. string replace only first instance python
  6. string.replace only first occurrence
  7. string.replace only one occurrence java
  8. string replace only first instance php
  9. string replace only first occurrence java
  10. string replace only first occurrence php
  11. string.replace only one occurrence c#
  12. string replace only once python
  13. string replace only
  14. python string replace only first occurrence
  15. js string replace only first
  16. javascript string replace only replaces first
  17. python string replace only last occurrence
  18. javascript string replace only first match
  19. c# string replace only last occurrence
  20. string replace javascript only once

Here is the problem, I need to create an image file with a .svg file. I have a function which should draw the svg, and then, i get it from a canvas to save it as an image file. my draw function is : ...

Here is the problem, I need to create an image file with a .svg file. I have a function which should draw the svg, and then, i get it from a canvas to save it as an image file. my draw function is : ...

  1. image onload firing
  2. image.onload not working
  3. image onload not working chrome
  4. image onload not working ie
  5. image onload doesn't work
  6. image onload javascript not working
  7. image onload function not working javascript
  8. image onload function not working
  9. jquery image onload not working
  10. canvas image onload not working
  11. firefox image onload not working
  12. react image onload not working
  13. safari image onload not working
  14. js image onload not working
  15. javascript image onload not working ie

I have an iframe that adjusts it's size dynamical. I solved this with a post message and a listener on the parent page, so everytime the content of the iframe changes the iframe size will too and ...

I have an iframe that adjusts it's size dynamical. I solved this with a post message and a listener on the parent page, so everytime the content of the iframe changes the iframe size will too and ...

  1. trigger function when div is visible
  2. trigger function when option is selected
  3. trigger function when checkbox is checked
  4. trigger function when div is loaded
  5. trigger function on page load
  6. trigger function on scroll javascript
  7. trigger function on checkbox click
  8. trigger function on click
  9. trigger function on oscilloscope
  10. trigger function on click jquery
  11. trigger function on enter key
  12. trigger function on window resize
  13. trigger function on select change
  14. trigger function on scroll jquery
  15. trigger function on state change react
  16. trigger function on click javascript
  17. trigger function on page load jquery
  18. trigger function on modal close
  19. trigger function on button click
  20. trigger function on load

is there a way to create a breeze predicate for a property that its type is Edm.Decimal? because the datatype in next expression is always double and I don't find a way to say to breeze that I just ...

is there a way to create a breeze predicate for a property that its type is Edm.Decimal? because the datatype in next expression is always double and I don't find a way to say to breeze that I just ...