Remove the click event from a single Div element - javascript

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

Related

Is it a scope issue?

I add a close button to the card. I try this code but the close button seems not working.
$('#add-pet').on('click', e => {
// Grab info from the form
let $name = $('#pet-name').val();
let $species = $('#pet-species').val();
let $notes = $('#pet-notes').val();
let $newPet = $(
'<section class="six columns"><div class="card"><p><strong>Name:</strong> ' + $name +
'</p><p><strong>Species:</strong> ' + $species +
'</p><p><strong>Notes:</strong> ' + $notes +
'</p><span class="close">×</span></div></section>'
);
// Attach the new element to the page
$('#posted-pets').append($newPet);
});
$('.close').on('click', function() {
$(this).parent().remove();
});
However, when I move this code:
$('.close').on('click', function() {
$(this).parent().remove();
});
right after the $('#posted-pets').append($newPet);
Then it works OK.
Why it is like that?
Whenever you want to make an event for an element which may be appended via jquery, you can try:
$(document).on('click', '.close', function() {
$(this).parent().remove();
});
It works after you appending span.close tag. Even if outside the scope
$('#add-pet').on('click', /*...*/);
Update:
You can also try:
$('#add-pet').on('click', e => {
let close_tag = $('<span>').addClass('close');
// do stuff...
// set event
close_tag.on('click', function () {
$(this).parent().remove();
});
$('#posted-pets').append(close_tag);
});
When the close function is outside of the div, it's trying to attach to existing .close elements and the element you are trying to attach to doesn't exist at that point in time. You need to do it inside because you need to have the $newPet element actually created before you can attach to it.
$('.close') will search in the dom.
If you haven't appended your html, then it can't be found by jQuery

Remove this and only this element jQuery

I am creating a dynamic list of tasks that appear after the input is written and input's length is less or equal 30 characters and the button is pressed.
Together with the task there is a trash icon created.
I want to enable the user to remove chosen task when he clicks on the icon which comes from the external library ionicons.
I have an issue that when the trash icon is clicked, it removes this Li and all Li elements that were created after that clicked Li.
I am prepending li elements to the list.
Here's the snippet:
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
$('.ion-trash-b').click(function () {
$(newTask).remove();
});
});
My question is:
How to remove only the one Li element which trash icon is clicked, and not all Li element (including the one) that were created later?
Thank you very much for your help.
$('.ion-trash-b').click(function(){
$(this).parent().remove(); // or $(this).closest("li").remove();
});
or even assign it onload to attach to all future trash icons using event delegation
$(function() {
$("#listContainer").on("click",".ion-trash-b",function(){
$(this).parent().remove();// or $(this).closest("li").remove();
});
});
where listContainer is the ID of the UL
Remove the closest li of the clicked ion-trash-b and as your elements are dynamically generated, use event delegation for ion-trash-b click event like following.
$('#addNewTaskBtn').click(function () {
var inputText = $('#dayTask').val();
var trashIcon = '<i class="ion-trash-b"></i>';
var newTask = $('<li />', { html: inputText + " " + trashIcon });
// clearing the input after click
$('#dayTask').val('');
if (inputText.length && inputText.length <= 30)
$(newTask).prependTo('ul.dayList');
});
$('body').on('click', '.ion-trash-b', function () {
$(this).closest('li').remove();
});

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

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/

Jquery on click event not working

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

Categories

Resources