several eventhandler in one function - javascript

Instead of creating a new function for every button handler i wanna create just one function and handle all the buttons there.I wanna the first button to do something different than the second one....My idea was to have one eventlistener but how do i know the target.id is the same as btn1 for example?
<div class="col-11" id="btns">
<button class="btn btn-dark" id="btn1">Button 1</button>
<button class="btn btn-dark" id="btn2">Button 2</button>
<button class="btn btn-red" id="btn3">Button 3</button>
<button class="btn btn-blue" id="btn4">Button 4</button>
</div>
let btn1=document.getElementById('btns');
btn1.addEventListener("click",doStuff);
function doStuff(e){
if(e.target.id===document.getElementById('btn1')){ //doesnt work
console.log("Hello");
}else if(e.target.id===.getElementbyId('btn2'){
//doSomething...
}
}

You have the right approach, there's just an error in your code:
e.target.id===document.getElementById('btn1')
This compares the ID of the element that was clicked to the element with the ID of 'btn1'.
That is, it compares a string to an element.
Naturally, this will always return false.
Instead, try:
e.target===document.getElementById('btn1')
This compares an element to an element.
Or:
e.target.id==='btn1'
This compares a string to a string.
Optional: You could simplify your code by using a switch/case block instead of a bunch of if statements. Here's how I would write your click handler:
function doStuff(e) {
switch(e.target.id){
case 'btn1':
// Do something for btn1...
break;
case 'btn2':
// Do something for btn2...
break;
}
}
More information about switch/case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Related

How to get the pressed button in a function

Is it possible to create a function that returns which button was pressed, even though all buttons have the same class?
It is important that the classes of the buttons must not be changed.
<html>
<body>
<button class="button">text</button>
<button class="button">text</button> //this button was clicked
<button class="button">text</button>
</body>
</html>
The code is only for visualisation I know it isn't right.
function myfunction(){
console.log(clickedbutton)
}
What I have to fill in so the code runs?
Sorry for the bad code i don't know how to make it more clearly.
Hello and happy new 2021!
I think this might be a slight duplicate of this.
As Gabriele said, you can get the HTML element by using the target. If you need some logic for differentiating the structures (using them in some state later on), you would need to assign an id or a different class.
Delegate
document.getElementById("buttonDiv").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("button")) console.log(tgt.textContent,"clicked")
})
<div id="buttonDiv">
<button class="button">text 1</button>
<button class="button">text 2</button>
<button class="button">text 3</button>
</div>
When an event happens and the handler that is bound to that event for that element is called, it is passed the event as the first parameter. And one of the properties of the event is the target which points to the element that triggered the event.
so
function clickHandler(event) {
const clickedElement = event.target;
console.log(clickedElement.textContent);
}
document
.querySelectorAll('.button')
.forEach(button => button.addEventListener('click', clickHandler))
<button class="button">text 1</button>
<button class="button">text 2</button>
<button class="button">text 3</button>
If you assign a function to the onClick event of a button (or multiple buttons), you can receive the event info as an argument, like so:
function myfunction(e) {
console.log(e.target.id)
}
<!DOCTYPE html>
<html>
<body>
<button id="button-1" class="button" onclick="myfunction(event)">text</button>
<button id="button-2" class="button" onclick="myfunction(event)">text</button>
<button id="button-3" class="button" onclick="myfunction(event)">text</button>
</body>
</html>
You can make use of data-id for getting index of button clicked.
const button = document.querySelectorAll(".button");
function getClickedIndex(evt) {
console.log(evt.target.getAttribute("data-id"));
}
button.forEach(button => button.addEventListener('click', getClickedIndex))
<html>
<body>
<button class="button" data-id="1">text</button>
<button class="button" data-id="2">text</button>
<button class="button" data-id="3">text</button>
</body>
</html>

How to fadeOut two children elements simultaneously using $(this)

I have a div in which there are 3 buttons. What I am expecting is that when I click the 3rd button, the 2nd and the 3rd buttons should fadeOut ... but in reality, only the 3rd button is fading out ... why so?
Here's, my code
<div id="bttns">
<button class="btn btn-danger"> Delete </button> //1st Button
<button class="btn btn-warning"> Modify </button> //2nd Button
<button class="btn btn-success"> Complete </button> //3rd Button
</div>
And here is the jQuery
$(".btn-success").on("click", function(){
$( $(this) , $(this).parent().children(".btn-warning") ).fadeOut(500)
})
I couldn't find a question similar to mine ... and also I am new to all of this so if you do find that such a question exists, please redirect me to it.
This happens becuse:
$( $(this) , $(this).parent().children(".btn-warning") )
this is not a valid selector here. To chain multiple jQuery objects you can use .add() method and then call .fadeOut(500) on the collection like:
$(".btn-success").on("click", function() {
var $btn3 = $(this);
var $btn2 = $(this).parent().children(".btn-warning");
$btn2.add($btn3).fadeOut(500)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bttns">
<button class="btn btn-danger"> Delete </button>
<button class="btn btn-warning"> Modify </button>
<button class="btn btn-success"> Complete </button>
</div>
As you have assigned classes. You can go like this :-
$(".btn-success").on("click", function () {
$('.btn-warning, .btn-success').fadeOut(500);
})
you are fading out only the button with the btn-warning class. instead use two selectors.
$(".btn-success").on("click", function(){
$(this).parent().children(".btn-warning, .btn-success").fadeOut(500)
})

How to capture two same id but different class in addEventListener

first of all, thank you for your time to read this question, and two things, I'm using ES5 and I don't use jQuery.
Right now I'm struggling a lot to figure what's the correct solution for the addEventListener, because for some reason it does not trigger for the second button which is only for the mobile screen dimensions, the problem is that the second button have the same id but different class, for example this:
<div class="product-bg-container product-general-info variation-info">
<input type="hidden" name="sku" value="Something-15892290" id="selected-option">
{/* Desktop screen button */}
<button id="buy-now" class="btn btn-lg hidden-sm-down btn-primary">
Add to Cart
</button>
{/* Mobile screen button */}
<button id="buy-now" class="btn btn-lg hidden-md-up btn-primary">
Add to Cart
</button>
</div>
Where I am trying to trigger the second button but it does not where I don't understand why it does, if the id is the same, should not matter, so I'm trying to figure how to trigger from the first button if it's clicked and also with the second if it's clicked, but I'm out of ideas...
var button = document.getElementById('buy-now');
if (!button) {
return;
}
button.addEventListener('click', function trackAddToCart() {
// more code for the event
}
I thought an idea to capture the attribute of the button, but it works in the first button but not for the second one:
var button = document.getElementById('buy-now');
var att = button.getAttribute('class');
button.addEventListener('click', function() {
console.log('class ' + att); //shows: class: btn btn-lg hidden-sm-down btn-primary
console.log('button class? '+ button); //shows: button element: [object HTMLButtonElement]
});
But when I click the second button... does not trigger or happening nothing, not sure why... and I can't change the id value (which it should be easy but I can't "company standard")
Can anyone help me to have an idea how to capture and trigger the event for the second button ??
The attribute id must be unique in a document. You can use attributeStartsWith selector or class with querySelectorAll(). Then loop through all the button to attach the event (click) individually:
//var button = document.querySelectorAll('.btn.btn-primary');
var button = document.querySelectorAll('[id^=buy-now]');
button.forEach(function(btn){
btn.addEventListener('click', function() {
console.log('class ' + this.classList);
console.log('button class? '+ this.id);
});
});
<div class="product-bg-container product-general-info variation-info">
<input type="hidden" name="sku" value="Something-15892290" id="selected-option">
<button id="buy-now" class="btn btn-lg hidden-sm-down btn-primary">
Add to Cart
</button>
<button id="buy-now2" class="btn btn-lg hidden-md-up btn-primary">
Add to Cart
</button>
</div>
nextElementSibling seems working in this case.
var btn1 = document.getElementById("btn");
var btn2 = btn1.nextElementSibling;
btn1.addEventListener("click",function(e){
console.log("btn1");
});
btn2.addEventListener("click",function(e){
console.log("btn2");
});
<div>
<button id="btn" class="btn1">butotn 1</button>
<button id="btn" class="btn2">butotn 2</button>
</div>

Multiple buttons with same class in jQuery

I have multiple buttons with the same class on my page, now when I try to call a method on the click event of the button, that method executes for all of the buttons because they have the same class.
The buttons on my page are dynamically created so I cant give different class to each button.
I am looking for a way to only execute some particular method on the click of the first element with the given class.
By using Jquery's .first() function, you can get the first element and then only bind the click event to it.
$(".sameClass").first().on("click", function() { console.log("clicked"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="sameClass">Button 1</button>
<button class="sameClass">Button 2</button>
<button class="sameClass">Button 3</button>
Here it is:
$("button").each(function(i, item) {
if(i === 0) {
$(item).on("click", function() {
console.log('works only for the first button');
})
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class"test-class">btn 1</button>
<button class"test-class">btn 2</button>
<button class"test-class">btn 3</button>
<button class"test-class">btn 4</button>
<button class"test-class">btn 5</button>
I'm looping through all buttons and adding event listener only for the first of them.

getElementById with multiple buttons

I'm struggling to get my links to enable their respective buttons. For instance the first link should enable the first button and the second should enable button 2.
Can anyone help?
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>
Your problem is your use of quotation marks. There are two options:
Use single quotes
Use " or \22 instead of your double quotes
Explanation
Your onclick is wrapped in double quotes. As soon as you use a double quote, it's the end of the onclick.
Solution
Link 1
Link 2
Demonstration
See this fiddle (Thanks #JamesThorpe for updating the escaped quote option)
Note, I removed the href because it doesn't make sense to link somewhere if you're going to do something on the current page.
removeAttribute(:attribute) can do the trick as well.
Link 1
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
Just change the quatation marks for the id from double to single ones:
document.getElementById('butt1').disabled=false;
If the anchor is just for the activation, add an return false at the end:
document.getElementById('butt1').disabled=false; return false;
Change the "butt*" with 'butt*' , otherwise the browser read this
onclick="document.getElementById("
and edit the href="link" with href="#" (this is not mandatory, but the question as it is now is a little strange)
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>
you problem in this string
"document.getElementById("butt1").disabled=false"
it should be
"document.getElementById('butt1').disabled=false"
Fiddle here
With a bit more work you start enabling a bit more elements, or add functionality that you could expand on easier in the future.
As a simple example, i added a small javascript file where you could set the elements that upon click activate/deactivate the other elements.
Currently i am preventing the default action, so you wouldn't be navigating towards the link you are actually setting, but that is entirely up to you ;)
;(function (ns) {
var actionElements = {
l1: ['butt1'],
l2: ['butt2']
};
function bootstrap() {
var prop, value, element;
for (prop in actionElements) {
if (actionElements.hasOwnProperty(prop)) {
element = document.getElementById(prop);
value = actionElements[prop];
if (element) {
element.addEventListener('click', function(e) {
if (typeof e === 'undefined') {
var e = window.event;
}
e.preventDefault();
for (var i = 0; i < this.length; i++) {
var el = document.getElementById(this[i]);
el.disabled = false;
}
return false;
}.bind(value));
}
}
}
}
ns.addEventListener('load', bootstrap);
}(window));
Link 1
Link 2
<button disabled class="btn btn-primary pull-left" id="butt1">Button 1</button>
<button disabled class="btn btn-primary pull-left" id="butt2">Button 2</button>

Categories