jQuery: create a div alert you when its is clicked, - javascript

I can't put a title to it. It's inception :)...
I have add div, when it is clicked, it creates alert div. When alert div is clicked it alert me.
that is an example.
$("#add").click(function(){
$("#add").after("<div class='alert'>Alert</div>");
});
$(".alert").click(function(){
alert("Here I am");
});
I noticed if I placed a div in the html template as <div class="alert">Alert</div> the alert will work. But if I added the div through the jQuery/JS it will not work.
what is the point of that?
to add more inputs and remove it in case he/she added too much, I noticed it didn't work and I wanted to know why:
this is the actual code:
$(document).ready(function(){
var i = $("#new_field_count").val();
//add new field
$("#addnew_field").click(function(){
i++;
$("#new_field").before("<div class='fivepadding'><input name='part1_" + i + "' type='text' placeholder='<?=lang('addform_p1')?>'> = <input name='part2_" + i + "' type='text' placeholder='<?=lang('addform_p2')?>'> <span class='remove clickable'><?=lang('addform_field_remove')?></span> </div>");
$("#new_field_count").val(i);
});
// remove the field
$(".remove").click(function(){
i--;
$(this).parent('div').remove();
$("#new_field_count").val(i);
});
});

For dynamically created content, use on.
$("#wrapper-div").on("click", ".alert", function(){
alert("Here I am");
};
Additionally, it's worth mentioning that it is adviced to use on instead of clickfor monitoring for example classes.
Rather than adding an event handler to every class element separately, the click event will bubble to the parent. According to the jQuery docs, it is a good idea to attach the handler to the closest relevant parent element (rather than the document).

Your document.ready block is interpreted once the DOM has finished loading. At that point in time, anything not in your DOM cannot have proper event binding. Here you can use delegation to make sure your bindings are going as planned. Since your 'body' will be loaded, you can target your .alert div for clicks as follows:
$("body").on("click", ".alert", function(){
alert("Here I am");
};

Related

How to restore JQuery events on removed element?

With this PHP I add the following HTML. I use PHP because I retrieve information from the database, but it's irrelevant in this question.
<?php
echo "
<div id='user_bio_container'>
<p id='user_bio'>My bio<i id='user_bio_edit' class='fas fa-edit'></i></p>
</div>
";
?>
This is the script I have. When the user clicks the bio paragraph, it stores the inside of the paragraph in a variable, then empties the container and adds a form. If the form is cancelled I want to remove the form and add the previous HTML I had in the paragraph. The problem is that when I try to do so the new paragraph does not respond to events (mouseover, click...).
$('#user_bio_edit').css("display", "none");
$(document).ready(function(){
$("#user_bio").on('mouseover', function(){
$('#user_bio_edit').css("display", "inline");
});
$("#user_bio").on('mouseleave', function(){
$('#user_bio_edit').css("display", "none");
});
$("#user_bio").on('click', function(){
var actualbio = $("#user_bio_container").html();
$('#user_bio_container').empty();
var user_bio_form =
"<form id='change_user_bio'>" +
"<span id='cancel_user_bio'>Cancel</span>"
"</form>";
$("#user_bio_container").append(user_bio_form);
//Button decision control
$("#cancel_user_bio").on('click', function(){
$("#user_bio_container").empty();
$("#user_bio_container").append(actualbio);
$('#user_bio_edit').css("display", "none");
});
});
});
I have tried using hide() and show(), but after two cancelled forms it stops working and I keep adding forms to the HTML that are not shown. I also tried moving the button decision control code outside the click event, but it does not work either.
This is a scope issue. actualbio is not available outside $("#user_bio").on('click', function(){..}
Change this
var actualbio = $("#user_bio_container").html();
to
actualbio = $("#user_bio_container").html();
and use
var actualbio = '';
just below
$(document).ready(function(){
this way the variable actualbio is available in all events handlers inside $(document).ready
Regarding the events not working issue
You need to attach events like this since #user_bio is removed from dom along with all attached events when you cleared the html.
$("#user_bio_container").on('mouseover', "#user_bio", function() {......})

Adding Jquery click handler to dynamically-loaded content

My Rails app loads links to a page dynamically. I want to append an onClick action to those links.
The links are appended to the page properly, but the JS for the page is not being applied to those newly added elements.
I've tried rendering new JS tags to the dynamically-added content. I've also tried including this block of code, which should target any link with .select-link added to the #links div.
$("#links").on("click", ".select-link", function() {
my code here...
})
That code works when the links are not dynamically loaded. However, I cannot seem to apply ANY onClick handler to them when dynamically loaded, even in the console.
What could possibly cause this issue?
For more context, the problem I'm trying to solve is here: AJAX-loaded JS not rendering
You should bind your event to document like this
$(document).on("click", "#links .select-link", function() {
my code here...
});
Try following code:
$(document).on("click", "#links .select-link", function() {
/*my code here...*/
})
or
$("#links .select-link").live("click", function() {
/*my code here...*/
})
The thing is, the code which you have in the question does work for dynamically inserted content.
The following snippet has one <div class="select-link"> which is part of the HTML and inserts two <div class="select-link"> elements via JavaScript.
jQuery is used to add two separate click handlers. The first handler is added prior to any of the dynamic content being added to the DOM. The second handler is added after the second <div class="select-link"> is added, but before the third one is inserted. Both handlers are called for all three <div class="select-link">. This demonstrates that the code you have provided in the question does work for dynamically inserted content. That means something else is going on.
$("#links").on("click", ".select-link"
,logEvent.bind(null,'#links on .select-link','jQuery'));
function logEvent(text,type,e){
var curTarget = (e.currentTarget.id)?e.currentTarget.id:e.currentTarget.nodeName;
var target = (e.target.id)?e.target.id:e.target.nodeName;
console.log(text + ' ::' + type + ' ::curTarget=' + curTarget
+ ' ::target=' + target);
}
function appendLink(id,text) {
document.querySelector('#links').insertAdjacentHTML('beforeend'
,'<div class="select-link" id="' + id + '" style="color:blue;">'
+ text + '</div>');
}
appendLink('sel-pre-ready','Selected Link 2 (added prior to document ready)');
$(document).ready(function(){
$("#links").on("click", ".select-link"
,logEvent.bind(null,'#links on .select-link','jQuery at doc ready'));
appendLink('sel-post-ready','Selected Link 3 (added after document ready)');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Not Link</div>
<div id="links">Links
<div id="not-sel">Not Selected Link</div>
<div class="select-link" id="sel-html" style="color:blue;">Selected Link 1 (HTML)</div>
</div><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
Without more information, spending a lot of time speculating on what might be causing the problem is just wasting time.
One possibility of what is happening is that another event handler is being fired for these events and stopping propagation. One way to (mostly) check for that is to add an event handler to the window on the capture phase (i.e. not using jQuery). You could do so with the following:
//The following will catch the event prior to almost all possible
// interference by other event handlers.
window.addEventListener('click',function(e){
if(!$(e.target).is("#links .select-link")){
return; //Not one of the elements we are interested in
}//else
//e.stopPropagation();
logEvent('on window','Capture',e);
},true);

.click() function being ignored

I'm generating list items that go in an unordered list. I then want to listen for a click on any of these list items. I'm aware I haven't posted the full code, but I'm hoping it isn't necessary for me to. Are elements that are appended like this completely ignored by my jQuery click function? I've tried just about everything and can't find out why! All I want to see is my "lol" alert! :(
$.each(entries, function(i, v) {
s += '<li';
if (favouriteItem(v.title)) s += ' data-theme="e"';
s += '>' + v.title + '</li>';
});
$("#linksList").append(s);
$("#linksList").listview("refresh");
$("li").click(function() {
alert("lol");
selectedEntry = $(this).data("entryid");
});
Although the items do visually appear the source code stays like this:
<div data-role="content">
<ul data-role="listview" id="linksList" data-divider-theme="b" data-inset="false"></ul>
</div>
Suggesting that there are no li elements there. Yet they do show visually? Someone please save me before I jump into a pool of lava.
Change:
$("li").click(function() {
alert("lol");
selectedEntry = $(this).data("entryid");
});
to
$('#linksList').on('click', 'li',function() {
alert("lol");
selectedEntry = $(this).data("entryid");
});
When you add elements dynamically to the document, you need to use .on()'s delegated event syntax.
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
Use delegation:
$("#linksList").on('click',"li",function() {
alert("lol");
selectedEntry = $(this).data("entryid");
});

Dynamically generated html elements stop working

In the following code I have some comments in an array which are displayed in a div using jQuery. Each comment has an options button which works fine until I post a new comment. I tried using unique IDs for each element but it didn't work either.
When the page loads, the options buttons work; but when I submit a new comment, none of the buttons work. What am I doing wrong?
Here's my script:
var i = 0;
var comments_display= "";
var comments = ['Hello World!', 'Hello! This is a comment.'];
//reads the entire array, creates the content, and sends it to the div
function show_comments(){
for (i=0; i<comments.length; i++){
comments_display += "<div class='single_comment_container'>";
comments_display += "<div class='comment_comment'>" + comments[i] + "</div>";
comments_display += "<div class='options'>Options</div></div>";
}
$("#comment_container").html(comments_display);
comments_display = "";
}
//appends a new comment to the array
function new_comment(){
if ($("#comment_input").val() == null || $("#comment_input").val() == ""){
alert("Your comment must be at least 1 character long.");
}
else{
comments.push($('#comment_input').val());
show_comments();
$("#comment_input").val("");
}
}
$(document).ready(function(){
show_comments();
$("#submit_comment").click(function(){
new_comment();
});
//display a message when an element of the class 'options' is clicked
$(".options").click(function(){
alert("OPTIONS");
});
});
And here's a fiddle to see how it works. http://jsfiddle.net/fahKb/3/
Thank you for taking your time to read this question.
You need to use delegation:
$(document).on( 'click', '.options', function() {
alert("OPTIONS");
});
http://api.jquery.com/on/
Note: You might want to use a static element other than document. (Some parent div that's always on the page or something.)
Just because you are adding elements dynamically so click won't work on those, so you have to find the closest existing parent on the page, here in your case is this comment_container and use the .on() handler: http://jsfiddle.net/fahKb/4/
$('#comment_container').on('click',".options",function(){
alert("OPTIONS");
});
$(document).on( 'click', '.options', function() {
alert("OPTIONS");
});
This first response is right, the cause of this is that when elements are loaded into the DOM you assign event listeners. Essentially saying hey if this is 'clicked' then do something. The problem is that when adding a new element you have NOT also added the event listeners. By doing something like the above code, essentially what you're doing is a search for everything within document that then has the class of ".options" and finally if it is clicked then acting and executing some code.
With that said using document isn't the most optimum method but it is sometimes necessary. A better solution would be if you were to wrap all the comments in say a "div" or some other element then pass that in place of document. This will instead of searching the entire document for the '.options', it would only search your wrapper eliminating alot of unnecessary work.
$('.commentWrapper').on( 'click', '.options', function() {
alert("OPTIONS");
});

Fade Out parent element of a link which was appended (with jquery)

I've got an empty div and I'm appending some text with html and two links in it. One link is normal with an href="some url" and the other is an element with a class. In short: this is a "yes | no" block. Yes is a normal url and NO is an element which will fade out the entire div.
The problem is that my div isn't fading out.
HTML:
(with css: display: block for hidding it from start)
JS:
// THE TEXT
var lbText = 'Thanks for helping us! Here\'s a preview of the part of gelattina you\'re about to take.';
lbText = lbText + '<br /><img src="img/g10/OldGelattina'+cpNum+'.jpg" />';
lbText = lbText + '<br /> YES | NO'
// I USE THIS CODE TO APPEND THE TEXT AND FADE IN THE ENTIRE DIV
$('.not-claimed').bind('click',function(){
$('#lightboxcont').empty().append(lbText).css({
'width': '30%',
'height': '30%',
'background': '#ffffff',
'zIndex': '9999'
}).fadeIn().center();
$('#lightboxOverlay').fadeIn();
});
The next code is what I'm using to hide de entire div
$('#lightboxcont a').bind('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
As I said, the problem is that the last jquery code isn't working and I don't know why.
I hope you understand, sorry for my english.
Jquery's bind method only is attached to matching elements that are available at the time it was first called. But they include the 'live' method which attaches to all matching elements now and that are created in the future. So if your appending the html after you bind the event try using:
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
Change bind to live. http://api.jquery.com/live/
Are you trying to attach the event to the <a> tags before you add them to the DOM? If you were to call that "next code" from inside the .not-claimed click event, after the append, it will probably work
Does your "click" function ever get executed?
Change bind to live. Bind won't work for dynamically added elements.
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
Thanks guys!!! the thing was solved using live instead of bind... I'm really really thankful!
$('#lightboxcont a').live('click',function(){
$("#lightboxOverlay").fadeOut();
$('#lightboxcont').fadeOut().empty();
return false;
});
Greetings!!

Categories