How can i add a event function after append a elements? - javascript

I click the button, it will append a div inside body, then, I want to click the div to alert a msg.I tried, but fail. How can I implements with highlight area.
example
$(document).ready(function()
{
$("button").click(function()
{
div = "<div class='test'>div</div>";
$("body").append(div);
});
$(".test").click(function()
{
alert("test");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Append div</button>

You should note that when document is ready elements with the .test class do not exist (that is why your code didn't work), they are dinamically added. So, I will do like this:
$(document).ready(function()
{
$("button").click(function()
{
var div = $("<div></div>").addClass('test'); // this is creating div element in dom as jquery
// Then attach click function to purpose of its create
div.click(function()
{
alert('test')
});
$("body").append(div);// then this is appending created div
});
});
jsfiddle Playground

One way, is just registering the listener on click event after you append it to the body tag, taking care of unregistering the previous clicks events, so you don't fall on multiple clicks events on the same element. Note that when document is ready still don't exists any element with the class .test, thats the reason your code was not working. Check next example:
$(document).ready(function()
{
$("button").click(function()
{
var div = "<div class='test'></div>";
$("body").append(div);
$(".test").unbind("click").click(function()
{
alert("A new div was clicked!");
});
});
});
.test {
width: 200px;
height: 200px;
background: red;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type="button">Append new div</button>
</body>

For dynamically created elements, use .on, lear more about .on here http://api.jquery.com/on/
$(document).ready(function(){
$("button").click(function(){
div = "<div class='test'></div>";
$("body").append(div);
});
$(document).on('click', '.test', function(){
alert("test");
});
});

Related

jQuery event listener fires before selector applied

I am trying to make a system that would require an admin to click a delete button twice before it fires the action. if he focusout of the button, it resets.
$(".unarmed").css("filter", "grayscale(1)").removeClass("armed").click(function(e) {
$(this).css("filter", "").removeClass("unarmed").addClass("armed");
}).mouseout(function() {
$(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
});
$("body").on("click", ".armed", function() {
alert("boom");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="plus.png">
I've seen jQuery event listener fires before selector applied? but adding e.stopPropagation() causes the second click to not fire.
when e.stopPropagation() is not in the code, it does fire the second click, but together with the first click (i think this means the problem is not with the second click selector)
here is a fiddle with e.stopPropagation():
https://jsfiddle.net/3jyr72t6/
also, if you have suggestion for making it prettier, i'm open for suggestions :D
#icecub answer as snippet:
$(document).ready(function() {
$(".unarmed").css("filter", "grayscale(1)");
$(".unarmed").click(function(e) {
if ($(this).hasClass("armed")) {
console.log("boom");
}
$(this).css("filter", "").removeClass("unarmed").addClass("armed");
}).mouseout(function() {
$(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="https://kns.im/include/img/plus.png" style="width:50px">
You can always just use the jquery dblclick event. Jquery dblclick
$(document).on("dblclick",".btn-delete",function(){
console.log("DELETE");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn-delete">DELETE</button>
You can use a simple function to detect click outside the element .. See the next example
$("img.unwait").on("click" , function(e){
let $this = $(this);
if($this.hasClass("unarmed")){
$this.removeClass("unarmed").addClass("armed");
}else if($this.hasClass("armed")){
alert("BOOM");
$this.removeClass("armed").addClass("unarmed");
}
});
detect_click_out(".armed" , function(){
$(".armed").removeClass("armed").addClass("unarmed");
});
function detect_click_out(element_selector , action){
$(document).on('click',function(e){
if (!$(element_selector).is(e.target) // if the target of the click isn't the container...
&& $(element_selector).has(e.target).length === 0) // ... nor a descendant of the container
{action();} // run the action as a function
});
}
img{
width : 50px;
}
.unarmed{
filter : grayscale(1);
}
.armed{
filter : grayscale(0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="https://png.pngtree.com/element_our/sm/20180515/sm_5afb099d307d3.jpg">

Checking if an element has a specific class in jquery not works

I am stopped up with a very simple functionality that worked with me many times back but not working right now.No specific errors in console also.
I am trying to check if there is a specific class for a div containing .form-content.inactive classes.I am trying to find if there is another class opened .
My codes are below mentioned
$(document).ready(function() {
if($('.form-content.inactive').hasClass('opened')){
$(".form-content a").click(function(event) {
alert('has');
});
}
});
No alerts are given on click.I am stupid now for a while :p
If your div hasn't the class opened from the beginning, you should do it this way.
$(document).ready(function() {
$(".form-content a").click(function(event) {
if($('.form-content.inactive').hasClass('opened')){
alert('has');
}
});
});
Otherwise your code could work.. When your div has the class opened already before the document became ready, only then jQuery is able to subscribe your click element to the event.
$(document).ready(function() {
if ($('.form-content.inactive').hasClass('opened')) {
$(".form-content a").click(function(event) {
alert('has');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-content inactive opened">
<a>Click!</a>
</div>
Instead of checking for opened you could use a delegate:-
$(document).ready(function() {
$('body').on('click', '.form-content.inactive.opened a', function(event) {
alert('has');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-content inactive opened">
<a>Link</a>
</div>
This will fire the click event for a if the .form-content has both classes .inactive and .opened.
If you insist on using hasClass and you have multiple .form-content then you should use this to get the closest .form-content and check for both classes.
$(".form-content a").click(function(event) {
var formContent = $(this).closest('.form-content');
if(formContent.hasClass('inactive') && formContent.hasClass('opened')){
alert('has');
}
});

jQuery - Hide a particular div until another is clicked and hide that div again when div is hovered off

Here is what I am trying to do. I have a button (#facebook-button) that when clicked will show the contents of a div (#facebook). Now I want it so when the mouse is not on top (hover) of the div #facebook that it then hides the div #facebook.
Here is what I have so far:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#facebook').hide();
jQuery('#facebook-button').click(function() {
jQuery('#facebook').show();
});
});
</script>
Any suggestions?
You can use jQuery's on mouseleave event, that event is fired when the mouse leaves the area.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#facebook').hide().on('mouseleave', function() {
jQuery('#facebook').hide();
});
jQuery('#facebook-button').click(function() {
jQuery('#facebook').show();
});
});
</script>
You can try some thing like this.
CSS
div { display: none; }
HTML
<a id="hover" href="#">Show</a>
<div id="div">Contents</div>
JS
$('#hover')
.mouseleave(function() {
$('#div').hide();
})
.click(function(e) {
e.preventDefault();
$('#div').show();
});
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#facebook').hide();
jQuery('#facebook-button').click(function() {
jQuery('#facebook').show();
$('#facebook').on('mouseenter', function() {
// do something or remove that part to just leave mouseleave
}).on('mouseleave', function(){
$('#facebook').hide();
});
});
});
</script>
Basically after showing the div, we will just spot when his mouse is leaving the #facebook div to hide it.
You could also optimize the code and put $('#facebook') in a variable considering the amount of time you re use it. Saves you calling jquery more times than actually needed.
Try this Demo.
$('.fbContent').hide();
$('button').hover(
function() {
$('.fbContent').show();
},
function() {
$('.fbContent').hide();
}
)

How to avoid events on elements behind others in HTML and JavaScript/jQuery

I have a table with some div's inside it.
I want an event to happen when I click on a td element, but I also want an event to happen when I click on a div element.
As you can see in this fiddle http://jsfiddle.net/rkGkp/1/ my problem is, when I click on the div element, both the div and td event is triggered, but I only want the div's event to be triggered.
I use these event listeners
$(function() {
$("#div").on("click", function() {
alert("a div is clicked");
});
});
$(function() {
$(".td").on("click", function() {
alert("a td is clicked");
});
});
What can I do to avoid the element behind my div to trigger an event?
Have a look here: FIDDLE
I used stopPropagation()
CODE
$("#div").on("click", function(event) {
event.stopPropagation();
alert("a div is clicked");
});
This is the easiest way to achieve what you need. Simply check if the click target is on the div:
$(function() {
$("#div").on("click", function() {
alert("a div is clicked");
});
});
$(function() {
$(".td").on("click", function(e) {
if(!$(e.target).is("#div")){
alert("a td is clicked");
}
});
});

toggle- hide item when click outside of the div

I am using jquery's slidetoggle, want to learn how to make the showup class hide when click anywhere outside of the DIV.
thanks!
Online SAMPLE: http://jsfiddle.net/evGd6/
<div class="click">click me</div>
<div class="showup">something I want to show</div>​
$(document).ready(function(){
$('.click').click(function(){
$(".showup").slideToggle("fast");
});
});​
.showup {
width: 100px;
height: 100px;
background: red;
display:none;
}
.click {
cursor: pointer;
}
​
Stop event propagation from within the .showup area:
$(document).on("click", function () {
$(".showup").hide();
});
Then prevent those clicks on .showup from bubbling up to the document:
$(".showup").on("click", function (event) {
event.stopPropagation();
});
Any click event that reaches the document will result in the .showup element being hidden. Any click events that start from within .showup will be prevented from proceeding any further up the DOM tree, and thus will never reach the document.
You will also need to stop any clicks on your button from traveling up to the document as well:
$(".click").on("click", function (event) {
event.stopPropagation();
$(".showup").slideToggle("fast");
});
Otherwise that click event will bubble up to the document and result in the hiding of .showup immediately.
Demo: http://jsfiddle.net/evGd6/2/
If you still want to record clicks on .showup panel (lets say you want it to be more then a simple informative panel), calling event.stopPropagation() on clicking it will make that panel untouchable/useless. Use event.cancelBubble = true instead and will let the event occur on .showup childs.
$('.click').click(function(){
$(".showup").toggle();
});
$(".showup").on("click", function (/*nothing here*/) {
event.cancelBubble = true
});
$(document).on("click", function () {
$(".showup").hide();
});

Categories

Resources