"$(...).find(...)" in onclick-eventhandler - javascript

I am using this code for the click handling on a button inside my page:
$(document).on("click", $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection"), function (e) {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
But the event fires as soon as I click anywhere in the page. Even if it is not the supposed button which I want to select with $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection") returns one element which is actually the button which I want to be selected.
Why does it behave like that?

If you want to use event delegation, the second argument should be a selector, not a jQuery object.
$(document).on("click", '#' + GlobalVariables.currentUserType + " .addDocumentToSection", function (e) {
// ---------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
If you don't want to use event delegation, you need to call on on the element you want to hook the event on:
$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function (e) {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});
This is all covered in the on documentation.

You are attaching onClick event to a document element. Try:
var button = $('#' + GlobalVariables.currentUserType).find(".addDocumentToSection");
button.on("click", function() {
addItemToDocumentGrid();
$('#removeDocumentFromSection').disable(true).addClass("disabled");
$('#removeSelection').disable(true).addClass("disabled");
});

$('#' + GlobalVariables.currentUserType).find(".addDocumentToSection").on("click", function(e){
});
jQuery can use selectors before the .on("click", this should work for you.

Related

JQuery on() method not binding events but works in console

I'm writing some TS code to generate a button dinamically, the button appear on page, but all events on it not works.
I already read answers about delegation and I using it, but the problem is not solved.
The most strange thing is that if I call $("#myID").click() or .mouseover() or .mousedown() in console, all events works correctly.
EDIT AND CLOSE:
Sorry for waste of time, I just put to my background the z-index css attribute to -100, and I don't know why, but the button was impossible to be clicked cause, even if it was visible, it was behind the background div.
Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $( "body" ).on( "click", "#commentForm .addNew", addComment ) use $( "#commentForm" ).on( "click", ".addNew", addComment ).
https://api.jquery.com/on/
I suspect your delegation is too complex. Consider the following example.
$(function() {
$("#add").click(function(e) {
var item = $("<div>", {
id: "image-button-1",
class: "button"
}).appendTo("#container");
$("<img>", {
src: "https://i.imgur.com/9yMnjGx.png"
}).appendTo(item);
});
$("#container").on("click", "#image-button-1", function(e) {
console.log("Click");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div id="container"></div>
Edit: Please don't refer to this, it is incorrect
Can you try this. Enclosing your logic in a function and passing it to jQuery ensures that it is called after the page is loaded completely.
When you are trying to bind event handlers to an element, you have to ensure that the element is actually present in the DOM.
this.htmlElement = "<div id='" + this.ID + "' class='" + this.cssClasses + "'>" + this.buttonImage + "</div>";
$("#" + this.idContainer).append(this.htmlElement);
$(function() {
if (this.enabled) {
$(document).on('mousedown', "#" + this.ID, function (event) {
console.log("down");
});
$(document).on("mouseup", "#" + this.ID, function () {
console.log("up");
});
$(document).on("click", "#" + this.ID, this.action);
}
});

jQuery `.parent().remove()` is not working

The solution may be obvious, but when clicking the .remove element, I am trying to remove the entire .tag element that is the parent. Currently, clicking the .remove element has no response.
HTML
'<div class="tag"><input id="' + id + '" type="hidden" name="' + name + '" value="' + value + '" />' + input + '<i class="remove dismiss fa fa-remove"></i></div>'
JS
$('.remove').on('click', '.remove', function() {
$(this).parent().remove();
});
Try this : As you are adding remove link dynamically, you need to register click handler using .on(). But in your case you have error in using .on(). Please use below code.
$(document).on('click', '.remove', function() {
$(this).parent().remove();
});
More Information on jQuery .on()
You can try this:
http://jsfiddle.net/myyzrwwe/
$('.remove').on('click', function() {
$(this).parent().remove();
});
You shouldn't always use delegate the event to the same element that has been delegated. You need to select a static parent. In my example, the document object is the parent of everything.
$('body').on('click', '.remove', function() {
$(this).parent().remove();
});
The problem might be you are binding the event to .remove, if this content is dynamic you might have a problem. Its better, in those cases, to bind to document.
$(document).on()
The callback has the event parameter, use that to remove.
function(e) {
$(e.currentTarget).parent().remove();
}
Check if you undelegate elements.

a href click not triggering in jquery

$(function() {
$.getJSON("companies.json", function(response) {
var html = '<table id="tbl">';
response.businesses.forEach(function(row) {
html += '<tr><td>' + row.id + '</td><td>' + row.name;
});
html += '</table>';
$("#tabledata").html(html);
});
$(".move").click(function() {
var $id = $(this).attr("idname");
$.getJSON("companies.json", function(response) {
$.map(response.businesses, function(obj) {
if (obj.id == $id)
console.log(obj);
return obj; // or return obj.name, whatever.
});
});
});
});
HTML:
<div id="tabledata" class='left'></div>
<div class="right"></div>
Please help?
As your .move element is added to your page dynamically, you have to make use of jQuery's on() method to delegate the event to an ancestor of the .move element which does exist when your JavaScript first loads.
$(document).on('click', '.move', function() { ... });
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
You can read more about jQuery's event delegation here.
If you use event delegation, your problem goes away (and your app becomes more performant and less prone to memory leaks).
// Only do this once, when your page loads...
$(document.body).on('click', '.move', function (ev) {
// This is the link that was clicked.
var $targ = $(ev.target);
});
Try This
$('#tabledata').on('click', '.move', function(e) { ... });
The reason the event isn't being triggered is because the event is only added to elements that exist on the page when you call the .click() method.
Instead, you can use event delegation:
$(document.body).on('click', '.move', function (ev) {
var $targ = $(ev.target);
});
which really says: call the function when any element that matches .move that's inside document.body is clicked.
I know others have said this already but I wanted to make event delegation clearer.

calling javascript function too many times

I'm just getting into Javascript and I've run into the same problem a number of times with different pieces of code: I have a function that creates a type of element and a function that does something with that type of element. It seems obvious to me that I need to call the "do something" function after the element has been created, but when I do, it ends up running more times than I'd like.
Here's an example of my problem:
function rightClick(){
$(".element").mousedown(function(e){
switch (e.which){case 3: alert( $(this).attr("id") )};
});
};
function doubleClick(){
var counter = 0;
$(document).dblclick(function(e){
counter++;
elementId = "element" + counter;
$("#new_elements").append("<div class='element'" +
"id='" + elementId + "'" +
"style='position:absolute;" +
"top:" + e.pageY + ";" +
"left:" + e.pageX + ";'>" +
elementId+ "</div>");
rightClick();
});
In this example, if I create 4 elements and I right-click on the first one I created, I end up getting 4 alert boxes instead of one. If I right-click on the second element I created, I get three alerts; the third: 2 alerts; the fourth: one alert.
Can anyone explain to me why this is happening, and how to fix it so that I only get one alert each time I right-click on an element?
Binding is the act of associating an event with a DOM element. The .mousedown and similar events only bind on elements that already exist.
Each time you call rightClick() you bind a new event to all current .element elements.
You can bind functions to the same element as much as you'd like, which is why you see the function being called many times.
For dynamic elements should checkout .on or .delegate which work like this:
Example of jQuery.fn.on
$(document.body).on("mousedown", ".element", function(e) {
if (e.which === 3) alert($(this).attr("id"));
});
Example of jQuery.fn.delegate
$(document.body).delegate(".element", "mousedown", function(e) {
if (e.which === 3) alert($(this).attr("id"));
});
Only call this once and you should be pretty much okay. If you're not using jQuery 1.7 or higher you will want to use .delegate() instead of .on.
You do not need to bind the event everytime you insert and element into the DOM. You can use .on to attach event handlers for elements that are dynamically inserted.
$(document).on('mousedown','.element', (function(e){
switch (e.which){
case 3: alert( $(this).attr("id") );
break;
};
});
var counter = 0;
$(document).dblclick(function(e){
counter++;
elementId = "element" + counter;
$("#new_elements").append("<div class='element'" +
"id='" + elementId + "'" +
"style='position:absolute;" +
"top:" + e.pageY + ";" +
"left:" + e.pageX + ";'>" +
elementId+ "</div>");
});
I believe you are adding the same handler several times, meaning that when you click a button you are re-binding the action to the same function.
You've bound your event handler to the class '.element'. This means that every element with the class '.element' on your page will fire that event when the right click occurs.

Why does my function get called twice in jQuery?

I have the following jQuery
$('img[title*=\"Show\"]').click(function() {
//$e.preventDefault();
var position = $('img[title*=\"Show\"]').parent().position();
$('#popover').css('top', position.top + $('img[title*=\"Show\"]').parent().height() + 150);
console.log(position);
$('#popover').fadeToggle('fast');
if ($('img[title*=\"Show\"]').hasClass('active')) {
$(this).removeClass('active');
} else {
$('img[title*=\"Show\"]').addClass('active');
}
});
I have two images with the title "Show Options." For some reason whenever I click on any of these images, it gets printed TWICE. When I only have 1 image, it only gets printed once. Why is this?
instead of $('img[title*=\"Show\"]') inside click function use $(this)
if doesn't works use:
$('img[title*=\"Show\"]').click(function(e) {
e.stopImmediatePropagation();
//other code
});
Use the following code
$('img[title*="Show"]').click(function (evt) {
$('#popover').hide();
$('img[title*="Show"]').removeClass("active");
$(this).addClass("active");
var p = $(this).parent();
$('#popover').css('top', p.position().top + p.height() + 150).fadeToggle('fast');
});
You can use event.stopPropogation so that event is not bubbled further. Maybe your function is being triggered from two different events and other one also get triggered while bubbling.

Categories