Problems onclick function on child button - javascript

I am trying to create a table, made with buttons, that allow me to get into a Geological Time Chart. I create 4 buttons with class "levels" and then I execute a function that return the childs from an API.
The point is that the function works the first time, but then it stop working for the new created buttons. Here is my code:
$(".levels").click(function clickLevel(){
var buttonName = $(this).text();
console.log($(this).text());
$.each(JsonObject, function(index,value){
if (buttonName == value.nam){
lvloid = value.oid;
console.log(lvloid);
}
if(lvloid == value.pid){
console.log(lvloid == value.pid);
var button = "<button class=\"btn-flat levels\" style=\"background-color:"+value.col+";\">"+value.nam+"</button>";
$(".conti").append(button);
}
});
});
I guess the problem is that I am creating the class within the function, but I don't find any other solution (I tried to declare the function and then call it in the .click event, but this don't even work!).
Thank you to all of you!!

Instead of :
$(".levels").click()
Use
$(document).on('click', '.levels', function(){
});
The reason behind this is, $(".levels").click() searches in the static dom, and you are generating the button dynamically. For dynamic content $(document).on() is used.

Use
$(".levels").on('click', function(){
});
instead of
$(".levels").click(function clickLevel(){
});

Related

Appgyver - JQuery on click not working for dynamically written items

I am writing a single page app using appgyver (javascript). There are a number of lists that are written dynamically using javascript (following an external API call). Each list contains an item which, when clicked / pressed, I would like to fire a different js method.
function write_a_list(some_array)
{
$('#some_list').html("");
for ( indexor =0; indexor < some_array.length; indexor++)
{
var this_option_div = $('<div>');
this_option_div.addClass('item');
this_option_div.addClass('some_list_item');
this_option_div.html("Button: " + indexor);
$('#some_list').append(this_option_div);
}
}
$(document).on('click', '.some_list_item', function()
{
supersonic.logger.debug('some_list_item clicked');
alert('some_list_item clicked');
});
For example, an array is passed to the write_a_list function. If an item is clicked it should be detected and fire an alert. However, this behaviour isn't observed. Is there a way that this can be achieved using the jquery 'on' approach?
You are using this_option_div.addClass('some_list_item'); and then calling the click event on an id that may not exist.
Change it to:
$(document).on('click', '.some_list_item', function() { ... }
EDIT ////
Can you try the closest parent selector that is not dynamic instead of document?
$('.static-wrapper').on('click', '.some_list_item', function() { ... }

JavaScript-How can I add an onClick function to a dynamically created button element?

Beginner programmer here-I am making an app that generates list items with a dynamically created button as a child of the 'li' element. I want to assign an onClick function to this dynamically created button but nothing seems to work. I have tried many ways, here is my most recent code.
var done = document.createElement("button");
done.onClick=function() {
alert("working");
};
done.innerText = "Finished!";
done.id = "deleteButton_";
The button generates fine but nothing happens when clicked. Any ideas? Thanks!
case matters
done.onClick=function() {
needs to be
done.onclick=function() {
better if you use addEventListener and not all browsers support innerText look into textContent
For use addEventListener, you could do something like
done.addEventListener('click', function (){
alert('working');
});
var iDiv = document.createElement('div');
iDiv.id = 'buttonDiv';
var button= document.getElementById('buttonDiv').innerHtml('<input type="button" onclick="myFunction(this)"');
function myFunction(button){
console.log(buton.id);
alert('pressed button with id :'+button.id);
}

Passing specific value to modal from dynamic buttons

I have a few different modals on my page that need data passed into them. I solved that problem with this other question, which has me using jQuery now and was really helpful. This is what I have now:
$(document).on("click", ".edit", function () {
$(".modal-body #value").val($('.edit').data('id'));
});
My problem is that since my page has dynamically created buttons (from a foreach based on the model), no matter which button I click, this gets the value from the first button. How do I instead get the value from the button that was clicked.
I thought about giving them all separate ids, but I don't want to make a function for each id. I read that there is a data property to this .on method, but I can't find a good example of how to use it and if it would work in my case.
If anyone has any suggestions I would be very grateful. Thank you!
$(document).on("click", ".edit", function () {
// Use $(this) to reference the clicked button
$(".modal-body #value").val($(this).data('id'));
});
You can reference the button being clicked by using the this keyword. Try the following:
$(document).on("click", ".edit", function () {
$(".modal-body #value").val($(this).data('id'));
});
Use Bootstrap's events:
$('#your-modal').on('show.bs.modal', function (e) {
var btn = $(e.relatedTarget);
var id = btn.data('id');
$("#value").val(id);
});
See the "Events" section of http://getbootstrap.com/javascript/#modals :
[The show.bs.modal event] fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

Can't listen to hover (etc) events after creating divs using innerHTML

So I generate some divs using this
document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>';
The problem I'm running into is that catching a hover event
$(".colorBox").hover(function(){
alert("!");
});
Won't work after doing that. Any thoughts?
EDIT:
To be more clear, check this out: http://graysonearle.com/test/16_t.html
I need to be able to have hover events happen after changing innerHTML that happen dynamically and many times. So like after changing the number of columns, the hover effect needs to work.
THANKS TO CHOSEN ANSWER:
For those in the future that might want to do something similar, my code looks like this now:
$(document).ready(function(){
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
$(document).on("mouseenter",".colorBox",function(){
if(mouseDown){
var clicked = $(this).attr("id");
var clicked = clicked.substring('box'.length);
next_color(clicked);
}
$(this).css("border-color","#ff0");
}).on("mouseleave", ".colorBox", function() {
$(this).css("border-color","#aaa");
});
$(document).on("click",".colorBox",function(){
var clicked = $(this).attr("id");
var clicked = clicked.substring('box'.length);
next_color(clicked);
});
});
whenever we update DOM from server side code or client side code.
For EX. DIV we are updating then it will not work with events we loaded before if we load that partial data.
so for this in document ready
code like this.
if you are using jquery 1.7+
then code like
$(document).on("hover",".colorBox",function(){
alert("Hi it will load after partial div update as well");
});
$(document).delegate(".colorBox","hover",function(){
alert("Hi it will load after partial div update as well");
});
and if you are using jquery 1.6 or less then that.
then use
$(".colorBox").live("hover",function(){
alert("Hi it will load after partial div update as well");
});
http://oscarotero.com/jquery/
If this helped you please mark as answer.
First, as you're using jQuery your first code could be simplified using the below function.
$('#container').append('<div class="colorBox" id="box'+i+'"></div>');
Second I think this is because you haven't declared the hover-off function.
$(".colorBox").hover(
function(){
alert("On");
}
);
Working Fiddle
You have to call your hover code AFTER injecting your divs. Jquery doesn't automatically listen to dom changes, so if you hook all your colorBoxes in $(document).ready(){...} and then insert a new div, nothing will ever happen.
So this works fine:
$(document).ready(function(){
for(i=0; i<5; i++) {
document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>';
}
$(".colorBox").hover(function(){
alert("!");
});
}

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");
});

Categories