$(this) not "refreshing" with $(document).on('click') - javascript

I'm using JavaScript (or jQuery) and I can't retrieve correctly the id of the button calling the event.
Here is a simplified example :
I have 2 buttons with the same class (the class is used for the listener) with id "button_1" and "button_2", I'll click on one of them, launch the event and get the correct id. Now, I'll click on the other button, launch the event and I still get the id of the first button.
Here is the code :
$(document).on('click', '.list-button' , function(e){
var target = e.target || e.srcElement;
var button_id = target.id;
alert(button_id);
}
or with jQuery :
$(document).on('click', '.list-button' , function(e){
var button_id = $(this).attr('id');
alert(button_id);
}
Both output only the first event caller. The second time, it'll launch the function but it's like " $(this) " is still the first event caller.
EDIT : I simplified too much my example, the alert is working fine and it was crashing later in the code. It was linked to wordpress and I had to undefine the variable to correct it. Thanks for your help even if my request was exceptionnaly useless, I guess you helped me to step back and reading step by step.

Your code works perfectly fine.
$(document).on('click', '.list-button', function(e) {
var button_id = $(this).attr('id');
alert(button_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="list-button" id="button1">Button 1</button>
<button class="list-button" id="button2">Button 2</button>
Make sure you check your HTML to have it right.

The code is working fine !
$(document).on('click', '.list-button', function(e) {
var target = e.target || e.srcElement;
var button_id = target.id;
alert(button_id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="list-button" id="button_1">Button 1</button>
<button class="list-button" id="button_2">Button 2</button>

Related

why is button toggle not working with class?

When I change my button toggle from ID-Name to Class-Name, the function is not working anymore. Does anyone know why?
I need a class since this button is multiple times on the page and loads in separately via css and sliders. The function and content is still the same.
$(document).ready(function(){
$('.infoBtn').on('click', function () {
var text=$('.infoBtn').text();
if(text === "info"){
$(this).html('close');
} else{
$(this).text('info');
}
});
});
The issue is your use of selector inside the click event:
$('.infoBtn').text();
Pointy:
Your code should use $(this), not $('.infoBtn') inside the handler.
What you have now will get the text only from the first one on the
page.
If you change that to $(this), it should work as required:
$(this).text();
$(document).ready(function(){
$('.infoBtn').on('click', function(){
//REM: Use $(this) and not $('.infoBtn')!
let text = $(this).text();
$(this).text((text === 'info') ? 'close' : 'info')
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class = 'infoBtn'>initial</button>
<button class = 'infoBtn'>initial</button>

I dont understand why my code isnt working

I am trying to the value of a button once it is clicked. But for some reason, the console keeps giving me an error saying buttonValue.addEventListener is not a function!!!
The following is my code:
var buttonValue = document.querySelector('.btn').value
buttonValue.addEventListener('click', function(){
console.log(buttonValue);
});
and here is my HTML code!:
<div>
<button class='btn' value="1">1</button>
</div>
try this:
you should have placed add event listener on the element, not the value of the element
var button = document.querySelector('.btn')
buttonValue.addEventListener('click', function(){
console.log(button.value);
});

Bind to jquery function issue

I'm using JQuery inside EcmaScript 6 class, and I have an event function which fires on instantiation of the class and the event contains different JQuery events which need to interact with the Class , so I do .bind() to achieve that, all works ok except one event which for some reason overrides this that belongs to jquery element "this" with "that" which I passed with .bind(that) method, here is my code (everything works exept for this event) :
var that = this;
$(document).on('click', '[select-file]' , function(event) {
event.preventDefault();
console.log(this);
}.bind(that));
so the console log gives me the parent class instead of jquery element
where as this works as expected:
$(document).on('click', '[open-file-dialoge]', function(event) {
event.preventDefault();
$('[file-dialoge]').modal('show');
if ($(this).attr('mitiupload') == 'false') {
// check if multiple upload is disabled
that.multiUpload = false;
$(this).removeAttr('multiple');
}
that.insertFiles();
}.bind(that));
Pleas help , I can't understand what is going on here one does not work as expected even though there is no big difference between them ;(
Function#bind() changes the context of this in a function. If you want the current element you can use event.currentTarget
var that = {};
$(document).on('click', 'button', function(event) {
event.preventDefault();
var el = event.currentTarget;
console.log('this=', this);
console.log('el=', el)
}.bind(that));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">Click me</button>

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

How can I remove a click event from an element in Javascript?

I have a <div> element that has a click event attached to it using the following code:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM, but need to first remove the click event
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
Any ideas?
Move the anonymous click handler function out of the addEventListener call:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);
The answer above is correct.
However, in case, someone is looking to remove the onclick function which is attached to a button like this for eg
<button type="button" onclick="submit()" id="tour-edit-save">Save</button>
In this case, to remove the onclick attached function, one will have to remove the attribute onclick and that would work perfectly fine.
Here is how you would remove using pure JavaScript
document.getElementById('tour-edit-save').removeAttribute('onclick');
Using jquery
$('#tour-edit-save').removeAttr('onclick');
Hope this helps someone who's looking for this answer.

Categories