addEventListener with multiple elements [duplicate] - javascript

This question already has answers here:
AddEventListener for multiple elements doesn't work with "focus" event
(3 answers)
Closed 6 years ago.
I started working with javascript.
I have two buttons, and want change backgroundColor when click on any of these buttons.
But my code doesn't work.
This is my code:
document.getElementsByTagName("button").addEventListener("click", function(){
func(this)
});
function func(element){
element.style.backgroundColor="gray";
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>
is there any way that an addEventListener works with multiple elements?

The best way is to have as few event listeners as possible in your code. So instead of attaching an event listener to each and every button, you can attach 1 single event listener to the area div and make suitable changes based on event.target attribute.
Run the below working code snippet:
document.getElementById('area').addEventListener('click', function(event) {
func(event.target);
});
function func(element) {
element.style.backgroundColor = "blue";
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>

You could do it like this or DEMO
var button = document.getElementsByTagName("button");
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.style.backgroundColor = "gray";
});
}
<div id="area">
<button type="button" class="btn" id="btn1">Play With Me!</button>
<button type="button" class="btn" id="btn2">Play With Me!</button>
</div>

Try this
<button type="button" onclick="myFunction()">Set background color</button>
<button type="button" onclick="myFunction()">Set background color</button>
<script>
function myFunction() {
document.body.style.backgroundColor = "red";
}
</script>

Related

how can i make buttons with numbers from 0-9 that adds into a textbox when i press them

I want to make a "numeric keyboard" that shows buttons with symbols from 0-9. When I press each button it is suppose to add up.
So lets say i press 3 , 4 then 1 it should say 341 on the text box or number box idk (srry im new).
I have only taken some examples from my teacher so i dont know if this is the right method.
I tried this on button 0:
<button onclick="showZero()">0</button>
<button onclick="">1</button>
<button onclick="">2</button>
<button onclick="">3</button>
<button onclick="">4</button>
<button onclick="">5</button>
<button onclick="">6</button>
<button onclick="">7</button>
<button onclick="">8</button>
<button onclick="">9</button>
<br>
<input type="text" id="txtZero">
window.onload = start;
function start() {}
function showZero()
{
var zero = document.getElementById("Number");
zero.Value="0";
document.querySelector("txtZero").appendChild(zero);
}
Am i using wrong method? I saw my teacher example, but he was using this to generate more buttons and not numbers like im trying to do.
EDIT: I edited my answer to provide a better answer that doesn't use inline event handling. I also wrapped the code into DOMContentLoaded event listener to make sure JS runs after the DOM is fully loaded.
function ready() {
// The textfield element
textField = document.getElementById("field")
// The reset button
resetButton = document.getElementById("resetbtn")
// Get all the buttons to an Array
buttons = document.getElementsByClassName("btn")
// Add click event listener to all button elements and insert their inner text as value to the text field
Array.prototype.forEach.call (buttons, (button) => {
button.addEventListener("click", () => {
textField.value += button.innerText
})
})
// Add click event listener to reset button
resetButton.addEventListener("click", () => {
textField.value = null
})
}
document.addEventListener("DOMContentLoaded", ready);
input, button {
padding: 3px 6px;
margin: 3px;
}
<button class="btn">0</button>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<br>
<input type="text" id="field"><button id="resetbtn">Reset</button>
Follow the code to it:
Add function setNumber to set number in field text.
Change function showZero to resetNumber if contains the value in field text insert zero.
function resetNumber()
{
document.getElementById("field").value = '0';
}
function setNumber(number) {
document.getElementById("field").value = document.getElementById("field").value === '0' ? '' : document.getElementById("field").value += number;
}
<html>
<body>
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="field" />
</body>
</html>

One function - many buttons

I have in HTML a button with id="button1".
We have JavaScript function:
$('#button1').click(function() { ... } );
It works well.
But what if we have 100 buttons with different IDs?
I can duplicate 100x function. However, this is not very elegant and good solution.
How to easily and effectively solve a problem for many buttons?
The function performed is the same for all buttons.
Add a class bind to this:
$(document).ready(function(){
//dot (.) selector binds to classes
$('.boundButton').click(function(){
//clicked button
var $this = $(this);
alert($this.attr('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="boundButton">1</button>
<button id="2" class="boundButton">2</button>
<button id="3" class="boundButton">3</button>
You need to use a class instead of ID. For example, your JS code could look like:
$('.button-class').click(function() { ... } );
and your HTML might look like
<button name='example' class='button-class' id='exampleID'>Button Text</button>
Here is the basic example:
$(document).ready(function () {
$(".btn").on("click", function(){ //attach click event to all buttons with class "btn"
console.log($(this).attr("id")); //$(this) refers to the button clicked
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>

Jquery change status of button on click

I have 6 Buttons, I gave each button a Default Status of false, if the user clicks on a button that corresponding Status is switching to true. Now if I Switch a button all other button Statuses shall switch to false.
Something like this worked but what is a good way to Code this for many Buttons, I do not want to repeat myself that much:
toolOneStatus = false
$('#btn-tool-one').click(function() {
toolOneStatus = true;
toolTwoStatus = false; ....
}
You can use .data() for this. Check snippet below...
$('button').click(function(){
alert('status ' + $(this).data('status'));
if($(this).data('status')=="false"){
//do this
} else {
//do this
}
$(this).data('status','true')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" data-status="false">Button1</button>
<button type="button" data-status="false">Button2</button>
<button type="button" data-status="false">Button3</button>
<button type="button" data-status="false">Button4</button>
<button type="button" data-status="false">Button5</button>
<button type="button" data-status="false">Button6</button>
You can use a single click function and identify the button by a data-no attribute.
This sample adds a blue color to the active button while all others remain gray. The activeButton variable represents the number of the active button.
var activeButton = 0;
$('.mybtns').click(function() {
activeButton = $(this).data('no');
console.log('active='+activeButton);
$('.mybtns').css('background-color','rgb(221, 221, 221)');
$(this).css('background-color','lightblue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybtns" data-no="1">Test1</button>
<button class="mybtns" data-no="2">Test2</button>
<button class="mybtns" data-no="3">Test3</button>
<button class="mybtns" data-no="4">Test4</button>
<button class="mybtns" data-no="5">Test5</button>
<button class="mybtns" data-no="6">Test6</button>
<button class="mybtns" data-no="7">Test7</button>
To loop through each of the buttons and execute some code for each, you can use the aptly named .each() function available in jquery. You can find the documentation for it here - each()
Whenever a button is clicked, .each() executes the function for all the elements with class=buttons and set the status=false. Inside the function you can use the $(this) selector to select the object of the current iteration. Finally outside the loop, the button which triggered the event, is given status=true.
$('button').click(function() {
$(".buttons").each(function(index) {
// Looping through each element having class "buttons"
$(this).data("status", "false"); //Setting every button to false.
$(this).next().html($(this).data("status"));
});
$(this).data("status", "true"); // Outside the loop, setting status true for the button which triggered the click event.
$(this).next().html($(this).data("status"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttons" id="button1" data-status="false">Button1</button><span id="p1"></span>
<button type="button" class="buttons" id="button2" data-status="false">Button2</button><span id="p2"></span>
<button type="button" class="buttons" id="button3" data-status="false">Button3</button><span id="p3"></span>
<button type="button" class="buttons" id="button4" data-status="false">Button4</button><span id="p4"></span>

A Button changing a CSS Element [duplicate]

This question already has answers here:
Pressed <button> selector
(5 answers)
Closed 5 years ago.
So I have this button:
<button type="button" class="close" data-dismiss="modal">Close</button>
and I have this CSS attribute:
.rouletteWheelGradient{
margin-top: 52;
}
Is that possible to change the 52px to 62px when the button is pressed?
Not with raw CSS, but this is certainly possible with JavaScript. First, we need to add a click function to the HTML to trigger the JavaScript:
<button type="button" class="close" onclick="move()" data-dismiss="modal">Close</button>
Then we need to build a function that moves .rouletteWheelGradient:
function move() {
for (var i = 0; i < document.getElementsByClassName("rouletteWheelGradient").length; i++) {
document.getElementsByClassName("rouletteWheelGradient")[i].style.marginTop = "62px";
}
}
Note the px at the end of the function, which represents pixels. You need to specify a unit of measurement for your selector, and you're missing this in your CSS.
Here's a working example:
function move() {
for (var i = 0; i < document.getElementsByClassName("rouletteWheelGradient").length; i++) {
document.getElementsByClassName("rouletteWheelGradient")[i].style.marginTop = "62px"
}
}
<button type="button" class="close" onclick="move()" data-dismiss="modal">Close</button>
<div id="1" class="rouletteWheelGradient">One</div>
<div id="2" class="rouletteWheelGradient">Two</div>
<div id="3" class="rouletteWheelGradient">Three</div>
The above sample gives every element with class rouletteWheelGradient a top margin of 62px when the button is clicked.
I've also created a JSFiddle showcasing this here.
Hope this helps! :)
Yes, with a little JQuery:
$('button.close').click(function(e){
e.preventDefault();
$('.rouletteWheelGradient').css({'margin-top':'62px'});
});
https://jsfiddle.net/wrunnvqa/2/
Yes, you can do it with some regular JavaScript.
Just add an id and onclick attribute to your button tag like so
<button id="btn" onclick="change()" type="button" class="close" data-dismiss="modal">Close</button>
then somewhere on the page you add a function inside a script tag
<script>
function change(){
document.getElementById("btn").style.marginTop= '62px';
}
</script>

On Button Click - Change Span Content - More efficient way?

I am looking for some assistance and there must be a better way to code this. I have a series of buttons that change the same span Id and well I can get it to work but it seems like an excessive number of actions. Is there a way to make this more efficient? Any help would be appreciated. Thank you!
jQuery("#All-Btn").click(function(event) {
event.preventDefault();
jQuery('#Type').html("red wine");
});
jQuery("#Awesome-Btn").click(function(event) {
event.preventDefault();
jQuery('#Type').html("Awesome");
});
You can use a custom function:
function myBtn(id, text) {
$(id).click(function (e) {
e.preventDefault();
$('#Type').html(text);
})
}
myBtn("#All-Btn", "red wine");
myBtn("#Awesome-Btn", "Awesome");
Well, provided you gave all your buttons a shared class and a data element you could reduce the logic as such.
<input type="button" id="All-Btn" class="typeButton" data-type="red wine">
<input type="button" id="Awesome-Btn" class="typeButton" data-type="some other value">
jQuery('.typeButton').on('click', function(e){
e.preventDefault();
jQuery('#Type').html(jQuery(this).data('type'));
}
Common Approach is using data attributes
$("[data-test]").on("click", function () {
var text = $(this).data("test");
$("#out").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button data-test="Red">Button 1</button>
<button data-test="Blue">Button 2</button>
<button data-test="Green">Button 3</button>
<div id="out"></div>
Another approach is a lookup
var text = {
btn1 : "Red",
btn2 : "Green",
btn3 : "Blue",
};
$(".btn").on("click", function () {
var id = $(this).attr("id");
$("#out").text(text[id]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<div id="out"></div>
Or a switch
$(".btn").on("click", function () {
var id = $(this).attr("id"),
text;
switch (id) {
case "btn1" :
text = "Red";
break;
case "btn2" :
text = "Green";
break;
case "btn3" :
text = "Blue";
break;
}
$("#out").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<div id="out"></div>
You could make object, with key-value pairs: Key is button id, value is span html, e.g:
buttons={
'All-Btn':'red wine',
'Awesome-Btn':'Awesome'
};
And then iterate through it:
$.each( buttons, function( key, value ) {
jQuery("#"+key).click(function(event) {
event.preventDefault();
jQuery('#Type').html(value);
});
});
buttons={
'All-Btn':'red wine',
'Awesome-Btn':'Awesome'
};
$.each( buttons, function( key, value ) {
jQuery("#"+key).click(function(event) {
event.preventDefault();
jQuery('#Type').html(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="All-Btn">
fffff
</div>
<div id="Awesome-Btn">
fffffffffff
</div>
<span id="Type"></span>
However, you have to type... a lot, again. :)
You can store the text that you want to display as an attribute of the button (ex data-text). Then, you just need one function to handle the event
jQuery("#All-Btn, #Awesome-Btn").click(function(event) {
event.preventDefault();
var text = jQuery(this).data('text');
jQuery('#Type').html(text);
});
How about that?
The first way that came to mind was to use a data- attribute to specify the text associated with each button, and then bind a single, delegated click handler to handle clicks on all buttons with that attribute.
Notice that then your buttons don't need IDs.
$("body").on("click", "[data-text]", function() {
$("#type").text($(this).attr("data-text"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="type"> </span><br>
<button data-text="Awesome">Awesome</button>
<button data-text="Whatever">Something</button>
<button data-text="Greetings">Hello</button>
<button data-text="Fare well">Goodbye</button>
<button>This button does nothing because it has no data- attribute</button>
(I've bound the delegated click handler to the body, but the best practice is to bind it to the closest common parent of the elements in question.)

Categories

Resources