Jquery on click event not working - javascript

I cant find why my code isn't working. When I click on the generated element the alert is not firing.
Here is a fiddle : http://jsfiddle.net/pZAdP/
And the code
<button id="addMenuItem">Add Menu Item</button>
<div id="content"></div>
function addMenuItem(){
var span = document.createElement("span");
span.setAttribute("id", "menu_" + inc);
span.innerHTML = " #menu_" + inc++ + " |";
var content = document.getElementById("content");
content.appendChild(span);
}
$("#addMenuItem").click(function(){
addMenuItem();
})
$("#menu_1").on("click", function(){
alert(this.id);
})

You need to change
$("#menu_1").on("click", function(){
alert(this.id);
})
with :
$("#content").on("click", "#menu_1", function(){
alert(this.id);
})
Working FIDDLE

You need to use event delegation for dynamically generated elements
You can use attribute starts with selector for all dynamically generated menu_
$("#content").on("click", "[id^='menu_']", function(){
alert(this.id);
})
Fiddle DEMO

You're using jQuery, so do it the easy way, add the event handler when you create the element, that way you don't have to worry about the incrementing ID in the selector either when you create more than one element
var inc = 1;
function addMenuItem(){
$('<span />', {
id : 'menu_' + inc,
html : '#menu_' + (inc++) + ' |',
on : {
click : function() {
alert(this.id);
}
}
}).appendTo('#content');
}
$("#addMenuItem").click(function(){
addMenuItem();
});
FIDDLE

http://jsfiddle.net/pZAdP/4/
Put your onclick for the menu inside the addMenuItem() function.
function addMenuItem(){
var span = document.createElement("span");
span.setAttribute("id", "menu_" + inc);
span.innerHTML = " #menu_" + inc++ + " |";
var content = document.getElementById("content");
content.appendChild(span);
$("#menu_1").on("click", function(){
alert(this.id);})}
Remember you are selecting by Id. If you were selecting by class then putting the on click handler outside the method will work.

You need to use the .on with event delegation
Syntax
$(parent-selector).on(event,target-selector,callback);
Note: The parent-selector must be parent element which is present in the DOM while binding the event, generally people use document and body, but for the performance you must have the nearest parent possible to the target
Example
$(document).on("click",".button",function(){
alert("Button Clicked");
});

Try this:
it will work for all dynamic span with id like menu_*:
var inc = 1;
function addMenuItem(){
var span = document.createElement("span");
span.setAttribute("id", "menu_" + inc);
span.innerHTML = " #menu_" + inc++ + " |";
var content = document.getElementById("content");
content.appendChild(span);
}
$("#addMenuItem").click(function(){
addMenuItem();
})
$(document).on("click", "[id^='menu_']", function(){
alert(this.id);
})

the element is not on the page when you select it,
do select generated elements:
$(document).on("click","#menu_1", function(){
alert(this.id);
})

Related

Jquery .replaceWith not working proper

i have a jquery code that is preventing a link to go to that link but executing it. The problem i have is that after it executs the script and script is returning data i want to replace it with a new one but with the same class. The replace is doing inside the dom but next time i press that link is not prevening going to that link but the class is the same, here is my code:
<script>
$(".recomanda").click(function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomandat</a> ');
}
if(data.recom==0)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});
</script>
html
<a class="recomanda" href="app/recomanda_produs.php?id='.$row['ID_Produs'].'&recom=0">Recomanda</a>
yeah, I ran into that problem too before, it's because when you attach click to recomanda on ready(), but when ajax load, everything in ready() won't fire again, that why you need to attach the event to non-dynamic elements, and let it find it's child selector.
$('body').on('click', '.recomanda', function() {});
When you call a replaceWith actually you are removing elements that are bound to onclick handler:
.replaceWith()
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
The main idea is that you handler must be bound to the same element (that is not removed when clicking).
So instead of using replaceWith method use method that modify existing element like this:
test.attr('href', blablabla);
And this is not a problem, but second time you don't need to use $ with test variable.
You need to delegate the event to a parent so that it can be applied to specific children wether they exist now or in the future.
See: http://learn.jquery.com/events/event-delegation/
$("body").on("click", ".recomanda", function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda"+((data.recom==1)?"t":"")+"</a> ');
}
if(data.recom==0){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});

Select an element after appending it in jquery

I appended an element:
$("#usernames_list").append("<li class='username_item'>" + item.username + "</li>")
Then I tried to select the newly appended element:
$(".username_item").bind('click', function(){
alert("asdas");
})
tried this also:
$(".username_item").click(function(){
alert("asdas);
})
alert function is not working.
How to fix this? All those other answers did not help
Your code should work as is but is not very effective.
Simplest and most effective way would be to keep reference of your created element so you won't have to research it again:
var $container = $("<li class='username_item'>" + item.username + "</li>");
$container.appendTo($("#usernames_list"));
this way you can register your listener easily :
$container.click(function(){
alert("asdas");
})
You can add it this way:
var $container = $("#usernames_list");
var liClick = function() {
alert("ok");
}
$container.on('click', '.username_item', liClick);
And here is example: http://fiddle.jshell.net/scg32rzh/3/

jQuery .on() event ignores selector

I have a function to create a div, ID it and add content before binding it to a click event using the .on() method using a selector as the second parameter. Here is the code I am using.
$('#overlayLeft').append(createOption('Item ID'));
function createOption(name){
var element = document.createElement('div');
var noSpaceName = name.replace(" ", "_");
element.id = 'toolOverlay' + noSpaceName;
element.innerHTML = '<input type="checkbox"><label>' + name + '</label>';
$('body').on('click', $('#' + element.id),function(){
alert("Test");
});
return element;
}
However instead of binding the click event to the body using the id of the generated element as the selector, the event acts whenever a click occurs on the body of the page.
How do I get the event to occur only on clicking the element without first creating the element and then binding the event separately?
You do not need jquery object, you need selector.use:
$('body').on('click', '#' + element.id,function(){
alert("Test");
});
also you can bind the click event without delegation using:
$('#' + element.id).click(function(){
alert("Test");
});
You have a strange mix of JQuery and native JS code. Maybe this works for your.
function createOption(){
return $('<div></div>')
.attr('id', 'toolOverlay' + name.replace(" ", "_"))
.append(
$('<input></input>')
.attr('type', 'checkbox'))
.append(
$('<label></label>')
.text(name))
.click(function(){
alert('test');
});
}
Try to put just selector string:
$('body').on('click', '#' + element.id,function()
That's not a selector that you are using, it's a jQuery object.
You can solve it by using just the selector, but instead of binding a lot of delegates to the body element, you can just bind the event on the element. That means that you don't need an id on the element to target it.
$('#overlayLeft').append(createOption('Item ID'));
function createOption(name){
var element = $('<div>');
element.html('<input type="checkbox"><label>' + name + '</label>');
element.click(function(){
alert("Test");
});
return element;
}
Binding global delegates is what the live method did, and it was deprecated because that is not a good way to use delegates.
If you're going to use jQuery, may as well use it everywhere. Note that the .click event is attached to the jQuery object/element as soon as it's created:
$('#overlayLeft').append(createOption('Item ID'));
function createOption(name) {
var noSpaceName = name.replace(" ", "_");
var div = $('<div>', {'id': 'toolOverlay' + noSpaceName})
.append('<label><input type="checkbox">' + name + '</label>')
.click(function () {
alert('test');
});
return div; // returns a jQuery object now, not a DOM element,
// which is fine when using .append() as you do here
}
http://jsfiddle.net/mblase75/bdvk9ssa/

Remove the click event from a single Div element

I have added a mousedown handler to all the divs inside a parent div, like this:
$productContainer.children(".button").on('mousedown', function(){
var index = $(this).index();
console.log("Clicked button at " + index);
// this doesnt work
$(this).removeAttr('mousedown');
});
Now I want to remove the mousedown handler after the button is clicked, for that particular div. How do I do that? Removing the attr mousedown doesn't seem to work.
Use the off method:
$productContainer.children(".button").on('mousedown', function(){
var index = $(this).index();
console.log("Clicked button at " + index);
$(this).off('mousedown');
});
More info: http://api.jquery.com/off/
You could also use the one method instead. It will automatically remove your event handler at the first time it is triggered:
$productContainer.children(".button").one('mousedown', function(){
var index = $(this).index();
console.log("Clicked button at " + index);
});
More info: http://api.jquery.com/one/
instead of :
$(this).removeAttr('mousedown');
use :
$(this).unbind('mousedown');
or
$(this).off('mousedown');
use .off
Description: Remove an event handler.
$productContainer.children(".button").off('mousedown');
$productContainer.children(".button").on('mousedown', function(){
var index = $(this).index();
console.log("Clicked button at " + index);
// this doesnt work
$(this).removeAttr('mousedown');
});

How to select element which is not 'this'?

I have list of divs all with the same class, I want to apply a function to all of them which are not the clicked one (this), how can i select !this with jQuery?
UPDATE:
I've made this and it is not working, any ideas why?
$("li").each(function(){
$("li").not(this).click(function(e) {
$(this).hide();
});
});
UPDATE 2: this is the whole actual code:
$(".mark").click(function(e) {
e.preventDefault();
var id = "#" + $(this).parent().parent().parent().parent().attr("id") + " ";
var currentStatus = "deleted"; // to be replaced with actual status
var currentStatusClass = "." + currentStatus + "-heading";
$(id + currentStatusClass).show();
$(id + ".edit-headings").click(function(){
$(this).find(".headings-status").show().addClass("bg-hover");
$(id + ".headings-status").click(function() {
$(id + ".headings-status").not(this).hide();
});
});
});
Have a look at jQuerys not function: http://api.jquery.com/not/
$('div').not(this).doSomething();
Regarding your update, try:
$("li").click(function(e) {
$("li").not(this).hide();
});
Use the .not() function:
$('.yourclass').click(function() {
$('.yourclass').not(this).yourFunc();
});
use $('div').not(this) to select other than clicked one.
using :not() or .not()
$this;
function myFunction(){
// stuff here // and use $this for element reference
}
$('yourElement:not(.selected)').on('click',function(){
// (make sure to add '.selected' to the new one and toggle existant)
$('.selected').removeClass('selected');
$this = $(this);
$this.addClass('selected');
myFunction();
});
this is wrong:
var newStatus = $(this).className().replace("contribution-", "");
className is not a function.
Instead of above line you can try this:
var cls = $(this).attr('class').replace('contribution-','');
$(this).removeClass().addClass(cls);

Categories

Resources