I want to create these buttons:
<!DOCTYPE html>
<html>
<body>
<button type="button">Linear algebra </button>
<button type="button">Calculus I </button>
<button type="button">Basic Mechanics </button>
<button type="button">Mechanics1 </button>
<button type="button">Mechanics2 </button>
<button type="button">Mechanics3 </button>
<button type="button">Mechanics4 </button>
<button type="button">Mechanics5 </button>
</body>
</html>
And I was wondering if there is an option to do it with a function for when the list is even longer.
My idea is to create the following list:
var subjects=["Linear algebra","Calculus I","Basic Mechanics","Mechanics1","Mechanics2","Mechanics3","Mechanics4","Mechanics4"]
And iterate it with a for loop and then create the button with the result of every element in the list. Is this possible?
You can use Array forEach to iterate through the array, use createElement to create the buttons and appendChild to append them to the DOM where needed.
var subjects=["Linear algebra","Calculus I","Basic Mechanics","Mechanics1","Mechanics2","Mechanics3","Mechanics4","Mechanics4"]
subjects.forEach(function(item){
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = item;
document.body.appendChild(button);
})
Related
<button class="btn" onclick="func(0)" value="">abc</button>
<button class="btn" onclick="func(1)" value="">def</button>
<button class="btn" onclick="func(2)" value="">ghi</button>
<script type="text/javascript">
function func(i){
var btn= document.getElementsByClassName("btn")[i];
console.log(btn);
btn.style.color="red";
}
</script>
I want to add new button every time, and want to display them on top. For adding them on top i need to change numbering till end
any solution to this. How new button[i] can be displayed on top
Subtract from the number of buttons to count from the end.
function func(i) {
var all_buttons = document.getElementsByClassName("btn");
all_buttons[all_buttons.length - i - 1].style.color = "red";
}
<button class="btn" onclick="func(2)" value="">abc</button>
<button class="btn" onclick="func(1)" value="">def</button>
<button class="btn" onclick="func(0)" value="">ghi</button>
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>
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)
})
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>
This question already has answers here:
How to insert an element after another element in JavaScript without using a library?
(20 answers)
Closed 4 years ago.
How to add line breaks between buttons in javascript? I want break tag
to be outside of the button elements.
html:
<button id="buttonOne"> click one me </button>
<button id="buttonTwo"> click on me too </button>
js:
var buttonOne = document.getElementById("buttonOne");
var lineBreak = document.createElement("br");
buttonOne.appendChild(lineBreak);
gives:
<button id="buttonOne"> click one me <br> </button>
<button id="buttonTwo"> click on me too </button>
what I want is:
<button id="buttonOne"> click one me </button>
<br>
<button id="buttonTwo"> click on me too </button>
var buttonOne = document.getElementById("buttonOne");
var lineBreak = document.createElement("br");
buttonOne.parentNode.insertBefore(lineBreak, buttonOne.nextSibling);
<button id="buttonOne"> click one me </button>
<button id="buttonTwo"> click on me too </button>
Try:
var buttonOne = document.getElementById("buttonOne");
var lineBreak = document.createElement("br");
buttonOne.parentNode.insertBefore(lineBreak, buttonOne.nextSibling);
after() should do it:
var buttonOne = document.getElementById("buttonOne");
var lineBreak = document.createElement("br");
buttonOne.after(lineBreak);
<button id="buttonOne"> click one me </button>
<button id="buttonTwo"> click on me too </button>