This question already has answers here:
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 4 years ago.
I have a really strange issue. I simply want to select a clicked element. I did this a lot of times and it always worked but this time, the jQuery $(this) selector doesn't select the clicked element, it selects the window object. Please let me know, if you have an idea, what could be the reason for this. I am using jQuery 2.1.4 and Twitters Bootstrap 3.3.5
HTML:
<a class="btn btn-danger btn-xs delete-file"><i class="fa fa-trash" aria-hidden="true"></i> Löschen</a>
jQuery:
$(document).ready( () => {
$('.delete-file').on('click', () => {
let element = $(this);
console.log(element);
});
});
Console-Output:
n.fn.init [Window]
instead of:
n.fn.init [a.btn.btn-danger.btn-xs.delete-file]
Thank you in advance!
It's because you're using an arrow function. The scope of the contents of this function do not change as per a standard function definition. For this to work you'll need to change the logic:
$(document).ready(() => {
$('.delete-file').on('click', function() {
let element = $(this);
console.log(element);
});
});
Alternatively you could keep the arrow function and retrieve a reference to the clicked element through the target property of the event that's raised:
$(document).ready( () => {
$('.delete-file').on('click', e => {
let element = $(e.target);
console.log(element);
});
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I need to attach an event to a dynamically created element. With jQuery I can archive this by using the following code:
$("body").on("click", ".my-element", function() {});
And if I added a new .my-element, it automatically got the event attached.
I'm not creating the elements via document.createElement("div");, but I'm using pjax to reload just some parts of the page, so the main JavaScript file just loads one time, for that reason events need to be attached dynamically.
How can I achieve that with vanilla JavaScript?
A pure JavaScript version of your jQuery example
$("body").on("click", ".my-element", function() {});
would be:
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
// handle event here
}
});
See example below.
const addTestElements = () => {
var el = document.createElement("p"),
node = document.createTextNode("Test element, class 'my-element'");
el.classList.add("my-element");
el.appendChild(node);
document.body.appendChild(el);
el = document.createElement("p");
node = document.createTextNode("Test element, class 'test'");
el.classList.add("test");
el.appendChild(node);
document.body.appendChild(el);
}
document.getElementById("add").addEventListener("click", addTestElements);
document.body.addEventListener("click", function (e) {
if (e.target &&
e.target.classList.contains("my-element")) {
console.clear();
console.log("An element with class 'my-element' was clicked.")
e.target.style.fontWeight = e.target.style.fontWeight === "bold" ? "normal" : "bold";
}
});
<button id="add">Add element</button>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I've got some cards (forms) created with ng-angular based on Array list.
On each card i have onClick event which doesn't trigger. If I copy paste the function code on browser console, all events work ! I guess that events aren't bind when the DOM is fully loaded.
These are my functions :
$('.floating-open').on('click', function () {
var $this = $(this);
$this.parents('.clickable-button').addClass('clicked');
$this.parents('.clickable-button').next('.layered-content').addClass('active');
setTimeout(function () {
$this.parents('.card-heading').css('overflow', 'hidden');
}, 100);
});
$('.floating-close').on('click', function () {
var $this = $(this);
$this.parents('.layered-content').prev('.clickable-button').removeClass('clicked');
$this.parents('.layered-content').removeClass('active');
setTimeout(function () {
$this.parents('.card-heading').css('overflow', 'initial');
}, 600);
});
Thanks in advance for your help
try to bind click event like below
$(document).on('click', '.floating-close', function(event) {
//your code
}
This question already has answers here:
How do I find out with jQuery if an element is being animated?
(5 answers)
Closed 7 years ago.
There are similar questions but this is some different and I could not find an adequate solution.
I've simple scroll function, it works well.
JS
$('#nextTabBtn').click(function () {
var leftPos = $('.whatever').scrollLeft();
$(".whatever").animate({scrollLeft: leftPos + 300}, 800);
});
HTML
<a id="nextTabBtn" class="btn btn-info">
<i class="fa fa-caret-right"></i>
</a>
The second click should be only possible, after the animation is done. A user may not click e.g. 10 times on the btn. For the second click he has to wait.
How can I do that with jQuery?
There are few ways to do what you are looking for, I usually do like this:
$('#nextTabBtn').click(function () {
var $target = $('.whatever');
if( $target.is(':animated') ) return;
$target.animate({scrollLeft: $target.scrollLeft() + 300}, 800);
});
After the object has been clicked, you could remove the click handler until the animation has completed, then re-add it again:
<script>
$('#nextTabBtn').on('click', handleClick);
function handleClick(event) {
console.log("Click");
$('#nextTabBtn').off('click', handleClick);
var leftPos = $('.whatever').scrollLeft();
$(".whatever").animate({scrollLeft: leftPos + 300}, 800, function(){
console.log("Finished");
$('#nextTabBtn').on('click', handleClick);
});
}
</script>
You can simply use a setTimeout(function(){/Your code here to halt the click on the button (you can also achieve it by disabling the button)/},10000); //10000 for 10seond
This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 7 years ago.
var vaStyle = $("nav.global_nav, .rsGCaption .intro-caption");
var vid_detach = $("div.rsCloseVideoBtn");
var vid_launch = $("h1#vidLaunch");
vid_launch.click(function () {
vaStyle.addClass("hprs-video-active");
});
vid_detach.click(function(){
vaStyle.removeClass("hprs-video-active");
});
Why isn't my removeClass working? Is there a better method?
Also, when you declare a var does it work document-wide?
Sounds like your elements are getting added dynamically. Use event delegation for solving this. I made changes to the event binding.
var vaStyle = $("nav.global_nav, .rsGCaption .intro-caption");
var vid_detach = "div.rsCloseVideoBtn";
var vid_launch = "h1#vidLaunch";
$(document).on('click', vid_launch, function () {
vaStyle.addClass("hprs-video-active");
});
$(document).on('click', vid_detach, function () {
vaStyle.removeClass("hprs-video-active");
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Ok so I have a button that when someone clicks it appends some info to a section.
like so:
function() {
$(".blend-tile").click(function() {
$(this).hide();
var li = $('<li><div class="align-table"><div class="color-img t-align"></div><div class="t-align"><div class="infora"></div><div class="percent-mix"></div><div class="mix-value"></div></div></div><div class="clear-tile">X</div></li>');
$('#mixers').append(li);
$('.tpic', this).clone(true, true).contents().appendTo(li.find('.color-img'));
$('.infora', this).clone(true, true).contents().appendTo(li.find('.infora'));
if ($('#mixers li').length === 6) {
$(".tiles").hide();
$(".nomore").show();
}
});
});
Which is all good work's fine.
But I also want all of this to remove() when I click <div class="clear-tile">X</div>.
and for that I am using:
$(function() {
$(".clear-tile").click(function() {
$(this).parent().remove();
});
});
But nothing happens no error nothing.
I also have similar function's in my file that use remove() and such which work fine. It's just anything that I try to trigger from .clear-tile just doesn't work at all.
I have a feeling it's down to me appending it but I'm not sure any help would be much appreciated
You need to use event delegation:
$("#mixers").on("click", ".clear-tile", function() {
$(this).parent().remove();
});
Instead:
$(".clear-tile").click(function() {
$(this).parent().remove();
});