Tough to come up with the title for this question.
More for proof of concept, I'm wondering why this doesn't work. What I'm attempting to do is use a jquery event to change the ID attribute, then use another jquery event bound to this newly changed ID.
For example:
<?php
echo <<<END
<html>
<head>
<style>
#before {
color:maroon;
}
#after {
color:blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
});
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
});
</script>
</head>
<body>
<p id="before">TEST TEXT</p>
</body>
</html>
END;
?>
On hover over my test text, the color changes from maroon to blue, as expected. It is my understanding that the text would now have an ID of "after" and the click event handler function would apply when clicked. However that is not the case the quick event handler and its associated alert does not appear to trigger.
I am new to jquery is there perhaps an update handlers function I'm overlooking?
It works with the same principle as Event binding on dynamically created elements?.
When you add a event handler to an element where the element is found using a selector, the selector is executed only once when the code is executed after that the handler is added to the element. Once is has happend if you change the selector values associated with the element it will not reflect in the attached handlers.
For example in your case you are adding the a handler to the element with id before in dom ready handler, so once the dom ready event is fired your selector is evaluated and it returns a single element to which you are adding the handler. In the same dom ready handler you are trying to add a click handler to an element with id after, but at dom ready there are no elements with that id so that handler is not attached to any element.
Now at a later time you are changing the id of the elemnet, but it will not affect in the already attached handler nor will it add a new handler.
The solution here is to use a mechanism known as event delegation.
Demo:
$(document).ready(function() {
//there is no need to use hover as your want to add the class when the mouse enter the element and you don't want to do anything in mouseleave
$("#mytarget").mouseenter(function() {
$(this).addClass("after").removeClass('before');
});
//look at the use of event delegation
$(document).on('click', '.after', function() {
alert("Handler for .click() called.");
})
});
.before {
color: maroon;
}
.after {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="mytarget" class="before">TEST TEXT</p>
You can fire the click event after the hover event
$(document).ready(function(){
$("#before").hover(function() {
$(this).attr("id","after");
$( "#after" ).click(function() {
alert( "Handler for .click() called." );
});
return false;
});
});
Related
I know we can bind event to dynamically created elements like below
$('some').on('click','class/id of dynamic ele',function(){});
but how to trigger click event on dynamically created element like i have created new element in dom
<div class="one">M</div>
now how can i $( ".one" ).trigger( "click" ); ?
$(document).on('click', '.one', function() {
use this one to put click on dynamically created element
find the DOCUMENTATION for more info
but how to trigger click event on dynamically created element like i
have created new element in dom
Try defining <div class="one">M</div> without attributes <div">M</div>; setting attributes at second argument to jQuery( html, attributes ) , utilizing .click()
jQuery( html, attributes )
html
Type: htmlString A string defining a
single, standalone, HTML element (e.g. or ).
attributes
Type: PlainObject An object of attributes, events, and
methods to call on the newly-created element.
Important: If the second argument is passed, the HTML string in the first argument must represent a simple element with no attributes.
As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data,
width, height, or offset.
// create dynamic element
$( "<div></div>", {
"class": "one",
"text": "abc",
"on": {
// attach `click` event to dynamically created element
"click": function( event ) {
// Do something
console.log(event.target, this.textContent)
}
}
}).appendTo( "body" )
// trigger `click` event on dynamically created element
.click()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Yup. .trigger() should do:
Snippet:
var myDIV = $('<div id="myDIV"> </div>');
$(document.body).append(myDIV);
$(document).on('click', '#myDIV', onClick);
function onClick() {
alert('hello');
}
myDIV.trigger('click');
div {
background-color: #cc0;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
But then again, if this is something you want to do when the document is ready or when the window has loaded, then you probably don't need to .trigger(), you can call the function directly.
Store that element in a variable, use the same to append dynamically in the body and then trigger click on it:
var div = "<div class='one'>M</div>";
$("body").append($(div));
//Your code//
$(div).trigger("click");
Or if there are multiple elements with same class and this is the last element then:
$(".one:last").trigger("click");
Did you ever try with delegate? if not you try like this for your dynamically added content.
$('body').delegate("div.one", "click", function(e){
// do you other works here
});
check this here
Hope your problem is solved. :)
As no FIDDLE provided, I have assumed the following markup
<a class="some">Click To Add</a>
<br/>
<div class="container">
</div>
css class
.one
{
background-color: Grey;
}
.some
{
background-color: Red;
}
Assigning click event after the control added to the DIV(with container class)
$(document).ready(function(){
$('.some').click(function(){
$('.container').append("<div class='one'>M</div><br/>");
$('.container div').off('click').on('click',function(){
alert("Clicked");
});
});
});
Try The FIDDLE, and share your inputs if any.
Hope this helps ............
i am posting this answer as in all the answers i can't see where to put this trigger method.
If you have any implementations like .append(), .html() of jquery or .innerHTML, .appendChild() of plain js then after execution of it, or i would say whenever you append your element in the DOM, right after it you can use any event to be triggered but some event has to be bound on it.
So, element has to be in the DOM to fire/trigger any event.
Take this example:
var div = $('<div id="aaa">aaa</div>');
$(document.body).append(div).on('click', '#aaa', divClik);
function divClik(e) {
alert(this.id+' clicked.');
}
div.trigger('click');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So, I'm having trouble with clicking events on elements, that were rendered by .html() function of jQuery.
Here's my code I'm testing with:
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="static/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="content">
<input type="submit" name="loginButton" id="loginButtonID"/>
</div>
<script>
$('#loginButtonID').click(function() {
$('#content').html('<button name="loginButton" id="newPasswordID">New Button</button>')
});
$('#newPasswordID').on('click', function() {
alert("alert");
});
</script>
</body>
</html>
As you can see, at the very beginning, I render a button with id="loginButtonID". I have .click() event on it, that creates in its turn another button by .html() (since .text() will return just HTML-code of that button) with id="newPasswordID" and for that button I have another event .on() as it should be (not .click()), but that event just doesn't work. So the question is: how to make that .on() event work for the second button?
Thanks.
The problem is that the #newPasswordID element doesn't exist as of when you try to hook the event. So since when you do $("#newPasswordID") it doesn't match anything, no handler is set up.
You can either do that after you render that element, or you can hook the event on some container that the element goes in (looks like #content) and use event delegation:
$("#content").on("click", "#newPasswordID", function() {
// ...
});
Since that really hooks click on #content, but then only fires it if the event travelled through an element matching #newPasswordID, it doesn't matter whether #newPasswordID exists as of when you hook up the event or not.
Try this:
$('#content').html(
$('<button />').attr('name',"loginButton")
.attr('id', "newPasswordID")
.click(function() {
alert('alert');
})
);
I simplified my code for next example. So, please don't be wondered why I'm using ajax here.
<!DOCTYPE>
<head>
<style>.not { background:yellow; }</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$(".not").click(function(e){
e.stopPropagation();
alert('good');
});
$(".click").click(function(e){
$.post('page2.php', 'q=1', function(data){
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}, "json");
});
});
</script>
</head>
<body>
<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>
</body>
New rows don't make any alert for class=not! It is inexplicably for me :'(
Thanks for unswer!
Assuming jQuery 1.7.x, use this:
$(document).on('click', ".not", function(e){
alert('good');
}).on('click', ".click", function(e){
if(!$(e.target).is('.not')) {
$('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
}
});
The problem is, .click will only bind to elements that exist when it's called. Using .on the way I'm suggesting delegates the click handling to the document element. By passing a selector as the second argument, you tell jQuery to run the event handler only if the event target matches the selector.
Put the $(".not")... part inside a function, such as disableNot = function() {$(".not").click......}. Then, after appending the new paragraph, call disableNot() to update the event handlers. (Also call disableNot immediately after defining it, so any .not elements already on the page are given their handlers.)
In your ready event handler, you use $('.not).click. click is an alias for bind, and bind only works on elements that are already in the DOM.
If you're using jQuery 1.7, you can use on instead, in its delegate-like form.
Here's index.html:
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn_test').click(function() { alert('test'); });
});
function add(){
$('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
}
</script>
</head>
<body>
test1
add
</body>
If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.
Could you explain it?
For users coming to this question after 2011, there is a new proper way to do this:
$(document).on('click', '.btn_test', function() { alert('test'); });
This is as of jQuery 1.7.
For more information, see Direct and delegated events
You need to use a "live" click listener because initially only the single element will exist.
$('.btn_test').live("click", function() {
alert('test');
});
Update: Since live is deprecated, you should use "on()":
$(".btn_test").on("click", function(){
alert("test");
});
http://api.jquery.com/on/
I have same problem like question I was just near to pulling my hair then i got the solution.
I was using different syntax
$(".innerImage").on("click", function(){
alert("test");
});
it was not working for me (innerImage is dynamically created dom)
Now I'm using
$(document).on('click', '.innerImage', function() { alert('test'); });
http://jsfiddle.net/SDJEp/2/
thanks #Moshe Katz
.click binds to what is presently visible to jQuery. You need to use .live:
$('.btn_test').live('click', function() { alert('test'); });
Use Jquery live instead. Here is the help page for it http://api.jquery.com/live/
$('.btn_test').live(function() { alert('test'); });
Edit: live() is deprecated and you should use on() instead.
$(".btn_test").on("click", function(){
alert("test");
});
This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.
$('.btn_test').live("click", function() { alert('test'); });
Jquery Live
you need live listener instead of click:
$('.btn_test').live('click', function() {
alert('test');
});
The reason being is that the click only assigns the listener to elements when the page is loading. Any new elements added will not have this listener on them. Live adds the click listener to element when the page loads and when they are added afterwards
When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.
Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.
You will have to manually bind the event to any new element, after it is added, or use the live listener.
$('.btn_test').click
will add the handler for elements which are available on the page (at this point 'test' does not exist!)
you have to either manually add a click handler for this element when you do append, or use a live event handler which will work for every element even if you create it later..
$('.btn_test').live(function() { alert('test'); });
After jquery 1.7 on method can be used and it really works nice
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("p").on("click",function(){
alert("The paragraph was clicked.");
$("body").append("<p id='new'>Now click on this paragraph</p>");
});
$(document).on("click","#new",function(){
alert("On really works.");
});
});
</script>
</head>
<body>
<p>Click this paragraph.</p>
</body>
</html>
see it in action
http://jsfiddle.net/rahulchaturvedie/CzR6n/
Or just run the script at the end of your page
You need to add a proper button click function to give a proper result
$("#btn1").live(function() { alert("test"); });
I have a HTML file that contains only the basic elements (html, head, body, ...) and I want to fill it up with content stored in an external file ("content.html") in my case, using JavaScript (and JQuery). I have accomplished that with function $.get(), but I don't know, how to access the information I got with this function.
For example, I want to throw an alert if a link is clicked. My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.get("content.html", addContent); // calls addContent
function addContent(data) // fills <div id='content'> with content.html
{
$("#content").html(data);
alert('Load was performed.');
}
$("a").click(function(event){ // !!!if any link is clicked, throw an alert
alert("Link clicked");
event.preventDefault();
});
});
</script>
</head>
<body>
<div id="content">
<!--CONTENT OF content.html WILL BE INSERTED HERE-->
</div>
</body>
</html>
This is how content.html looks like:
<h1>Band Creator Home</h1>
<p>Currently following apps are available:</p>
<ul>
<li>Bands</li>
<li>Instruments</li>
<li>Musicians</li>
<span></span>
</ul>
Since there is no element in the original HTML, alert "Link clicked" is never thrown. How can I access these elements collected by $.get() ?
You are looking for .live() bindings. Do it like:
$("a").live('click', function(event){ // !!!if any link is clicked, throw an alert
alert("Link clicked");
return false;
});
The event method .preventDefault() does not work within .live(), return false instead. Since .live() adds an even listener to the document.body, it's always a good idea to use .delegate() if possible. You can tell .delegate the closest parent node which all elements share you need to watch. In your instance:
$('ul').delegate('a', 'click', function() {
alert('Link Clicked');
return false;
});
Ref.: .live(), .delegate()
AJAX is asynchronous.
The server only sends a reply some time after the get method finishes.
Therefore, you end up adding the click handler before addContent is called, before the new elements exist.
If you add the handler inside addContent, it will work fine, since the new element will have already been added.
Alternatively, you can use jQuery's live method to add a handler to all elements that match the selector, no matter when they were created.
An alternative to the live method is using delegate on some parent of the newly created elements. This is useful if you don't want the event to be propagated to the top of the DOM hierarchy.
$("#parentofa").delegate("a", "click", function(event) {
// ... my handler
event.preventDefault();
})
The <a> element that was clicked is stored in event.target
Note that preventDefault is working here but that the event has already been propagated until the parent element (i.e. all elements in between have received the element already)
There are some different ways. You can set the events after loading the content:
function addContent(data) {
$("#content").html(data);
alert('Load was performed.');
$("#content a").click(function(event){
alert("Link clicked");
event.preventDefault();
});
}
You can use the live method to catch the even when it bubbles up:
$("a").live('click',function(event){
alert("Link clicked");
event.preventDefault();
});
If you are using version 1.4.2 or later of jQuery, you can use the delegate method, which is like the live method, but you can check for bubbling events in a closer scope than the body:
$("#content").delegate('a', 'click',function(event){
alert("Link clicked");
event.preventDefault();
});