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>
Related
My Jquery one() function dies after second click instead of first click. Here is my HTML
<div class="box">
<div class="call" data-tai="5">CLICK</div>
</div>
and heres my Jquery
$('body div').one('click', '.call', function() {
var mother = $(this).parent();
if(mother.css('position') === 'static')
mother.css('position', 'relative');
var tai = $(this).data('tai');
$.ajax({
method: 'GET',
url: '/bootstrap/call.php',
data: 'tai='+tai,
dataType: 'html',
success: function(ret) {
mother.append(ret);
},
});
return false;
});
Interesting thing is, if i don't use return false;, it dies after first click. However bubbling occurs and it appends 2 html tags instead of 1, inside box element. Thanks for help
$('body div')
would select both the divs and attach click handlers to both of them. When you click on the nested div then, both clicks will be fired. Use a specific selector to avoid this.
$('.call')
could perhaps achieve this.
That's because event handlers bound by using .one will be fired once for each element in the jQuery collection. Since the return false stops the propagation of the event, if you click on the .call element, click handler of the parent element is not executed but the parent element still has an active click handler. You should use a more specific selector for selecting the target element. If the click handler should be bound to the div.call elements:
$('.box div.call').one(...);
Now, if .box elements have 9 div.call descendants then you have 9 click handlers! After clicking on each element jQuery unbinds the handler for that specific element.
It's not once for all elements, it's once for each element.
If the handler should be called once for all the matching elements you can use the delegation version of the .one method:
$(document).one('click', '.box div.call', function() {
// ...
});
And if you want to delegate the event and have the handler working once for dynamically generated elements you can use the .on method and :not selector:
$(document).on('click', '.box .call:not(.clicked)', function() {
$(this).addClass('clicked');
// ...
});
Now the handler is called once for each .call element. Since :not excludes the elements that have .clicked class the selector doesn't match the already-clicked elements.
Events bubble in JavaScript. Your code
$('body div').one('click', '.call', function() {
}
wires up on both
<div class="box"> <!-- This -->
<div class="call" data-tai="5">CLICK</div> <!-- And this -->
</div>
You need a more specific selector. If this div is a parent element in the body like this:
<body>
<div class="box">
<div class="call" data-tai="5">CLICK</div>
</div>
<div class="box">
<div class="call" data-tai="5">CLICK</div>
</div>
</body>
then you can use a selector like this:
$('body > div').one('click', '.call', function() {
}
The question is - where do you expect your click event to be placed? Perhaps the div with the box class?
$('div.box').one('click', '.call', function() {
}
This assumes that the .call divs are being added dynamically to the .box div.
P.S. - if you want to stop the bubbling, I suggest you pass in the event object to your click event and call stopPropagation()
$('div.box').one('click', '.call', function(evt) {
evt.stopPropagation(); // no bubbling
}
I am trying to print out the full HTML of the DOM element with limited success. I would like to know if there's a helper in JavaScript that's intended to do just that.
this.div.click( function(e) {
alert(e.target);
alert(e.target.tagName);
alert(JSON.stringify($(e.target).parent()));
});
I am expecting to get something like:
<div class="gameActivator AnyItem-Off-selector UI-Widget UI-Content"><span class="content widget-inner"><button class="activateButton"></button></span></div>
Use currentTarget to get the element on which the event listener was originally attached. Then you can read all the HTML of that element with outerHTML.
this.div.click( function(e) {
console.log(e.currentTarget.outerHTML);
});
A live demo at jsFiddle.
You can use this.outerHTML. Inside a jQuery event handler this is the current element
this.div.click( function(e) {
console.log(this.outerHTML);
});
Use innerHTML or outerHTML, depending on wether you want to include the given element in the returned HTML.
this.div.click( function(e) {
console.log( this.innerHTML );
console.log( this.outerHTML );
});
In jQuery it would be just html()
console.log( $(this).html() );
I trying to run code to change div id,class,... in every click but I don't
know how this my js code :
<div class="up_vote_bt upvote_hide" title="Delete up vote" onclick="upvoteHide()" id="hideupvote"></div>
<script>
$(document).ready(function() {
$("#upvote").click(function() {
document.getElementById("upvote").setAttribute("class","up_vote_bt upvote_hide");
document.getElementById("upvote").setAttribute("title","delete up vote");
document.getElementById("upvote").setAttribute("onclick","hideupvote()");
document.getElementById("upvote").setAttribute("id","hideupvote");
});
});
</script>
<script>
$(document).ready(function() {
$("#hideupvote").click(function() {
document.getElementById("hideupvote").setAttribute("class","up_vote_bt");
document.getElementById("hideupvote").setAttribute("title","up vote");
document.getElementById("hideupvote").setAttribute("onclick","upvote()");
document.getElementById("hideupvote").setAttribute("id","upvote");
});
});
</script>
if you're using jQuery why not do this?
$(document).ready(function(){
$('#upvote').click(function(){
//$(this) for just this element
if($(this).hasClass('upvote_hide')){
$(this).attr('title','Up vote');
upvote();
}else{
$(this).attr('title','Delete up vote');
hideupvote();
}
$(this).toggleClass('upvote_hide')
});
});
toggleClass() will either add or remove upvote_hide if it doesn't exist or exists.
attr() will alter the attribute much like setAttribute()
For my example there is no need to alter the eventHandlers or in your case setting the attribute onClick to the function. I'ts all done in the jQuery event hander function. So your functions that you're passing to the onclick attribute are called within the function.
When you attach an event handler via jQuery using the
$("#upvote").click(function() { ... });
mechanism, jQuery will directly attach the handler to the elements in the query result set. This means that the handler will be there, whatever the ID changes to in the future.
What you can do is to attach a delegated handler to the document like this.
$(document).on("click", "#upvote", function() { ... });
$(document).on("click", "#hideupvote", function() { ... });
See this article for a deeper explanation
Also, setting the onclick attribute is meaningless in this case and you should remove those lines.
However, changin IDs of elements is not a good practice. An ID should mean a unique identifier for a DOM node, which is not expected to change. I would rather toggle classes here.
var div = document.createElement('div');
div.setAttribute('class', 'asd');
parent.appendChild(div);
This code basically creates a div and appends it inside the parent element.
$(".asd").hover(function(){
alert("hey");};
This one is a function when hovering the created div. But it doesn't work. Any solution?
You forgot a closing parenthesis:
$(".asd").hover(function(){
alert("hey");
});
But really, if you're adding the element dynamically, you should change your hover event to one that uses mouseover and mouseout, and use event delegation so that your event can be caught as it bubbles up the event ladder (or whatever it's called):
$(document).on('mouseover', '.asd', function () {
console.log('on')
}).on('mouseout', '.asd', function () {
console.log('off')
});
And you if you're going to use jQuery I'd suggest that you use it for all your DOM manipulation. Using document.createElement and jQuery is kinda strange.
DEMO
Sure, but you'll need to use event delegation:
$(document).on('mouseenter', '.asd', function() {
// do stuff here
}).on('mouseleave', '.asd', function() {
// undo stuff here
});
This applies the event listener to some ancestor element that exists on DOM load, and only runs the function if the event target is the element listed as the second argument.
This method allows you to add elements to the page at will without having to create new hover listeners. Any element with class asd will have the listeners attached.
If performance is a concern, substitute any ancestor element that's available on DOM load for document to reduce the scope of the listener.
http://api.jquery.com/on
Please enclose all the code in DOM ready or put the code at the bottom of the page:
Note: For this demo, I added function() {} as the second parameter of hover so that the alert does not appear twice ... I could/should have used focusin event.
$(function() {
var parent = $('.parent')[0];
var div = document.createElement('div');
div.setAttribute('class', 'asd');
parent.appendChild(div);
$(div).hover(function() {
alert("hey");
}, function() {});
});
.asd {
border: 1px solid #000;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent"></div>
event delegation is wrong on dynamically created div and there is a parentheses mistake
write it like this
$(document).on(hover,"asd"function(){
alert("hey");
});
Plus you can leave creating div to jquery
parent.appendChild('<div class="asd"></div>');
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;
});
});