I have researched on the web and tested for a solution for quite a while, but have not been able to make this work. So I have decided to create a post here, even though its probably low-skilled and I'll get downvoted for it I have put a lot of effort and I hope someone can help out.
My code at the moment uses .click() function from JQuery and my goal is to use it on a button so that when I click that button, it checks whether the id of the button clicked on matches a variable that I set in the .js file. In other words, check if the thing I clicked on's id is equal to my "target".
This is the part of the code with the problem:
var target = '#vig_but_inc';
$(this).click(function() {
if(this.id == target) {
vigor.incStat(); // increase stats once
console.log("hi"); // test if code fires
$('#vig_res').html(vigor.current);
}
});
Please note I have checked if the code works without matching the id, without the if-statement - in that situation if I click on a specific, preset button's id I managed to increase the value of #vig_res which is my goal.
However with the if involved, as explained prior, I am trying to match what is being clicked on with my target, which is the id name I wish it to match to. I'm using this to check my click, which has worked in other areas but doesn't seem to work in this context.
I have made the variable target global scope as explained here in the comments: Check if the clicked div id matches with variable. It still doesn't work.
I know and have tested $(this).click(.., where it would fire off the code inside of whatever div I clicked. So I believe the problem lies afterwards, maybe in the this.id, but I've also used .is() like suggested elsewhere but it won't work that way either.
I hope someone can give me some insight into how to tackle this problem, thank you.
The answer is a little more complicated, in the anonymous function which is called when the click is triggered, this is not the clicked element, it is a jQuery object. You should accept as first parameter event and use event.target. Plus, target should not contain the #, because the .id returns only the name.
So, your code should look like this:
var target = 'vig_but_inc';
$(this).click(function(event) {
console.log(event.target);
if(event.target.id == target) {
vigor.incStat(); // increase stats once
console.log("hi"); // test if code fires
$('#vig_res').html(vigor.current);
}
});
Working Fiddle: https://jsfiddle.net/e8np0g9j/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With