I'm trying to set up a listener for a button that does not have an ID. How would I create a listener for the following element:
<button class="jss459 jss433 jss444 jss445 jss447 jss448 jss321" tabindex="0" type="button" title="Press Enter"><span class="jss434">Quick Search</span><span class="jss471"></span></button>
const myelement = document.querySelector('.jss459.jss433.jss444.jss445.jss447.jss448.jss321');
or
const myelement = document.querySelector('[title="Press Enter"]');
But you'd probably be better off with a more unique selector :)
querySelector()
It allows You to grab the element by the class name
const button = document.querySelector(<classHere>);
button.addEventListener('click', ()=> {
//code here
})
You can use document.querySelector to return the first element that matches the selector, for example:
document.querySelector('button').addEventListener('click', event => {
console.log('The button was clicked');
});
<button class="jss459 jss433 jss444 jss445 jss447 jss448 jss321" tabindex="0" type="button" title="Press Enter"><span class="jss434"> Quick Search</span><span class="jss471"></span> </button>
It sounds to me that you ONLY want to select a button that doesn't have an ID attribute. In that case, you can use querySelectorAll to select all the buttons on the page and then add an Event Listener the buttons that don't have the ID attribute. Below would be the code for that:
let allButtons = document.querySelectorAll('button')
allButtons.forEach( button => {
if (!button.hasAttribute('id')) {
button.addEventListener('click', buttonWithoutId)
}
})
function buttonWithoutId() {
alert('this button does not have an ID!')
}
Related
I was curious about how I could make a normal button, with a "selected" style or animation.
<button> I'm a button </button>
When you use Radiobuttons, you can see clearly that you have a selected style whenever you click on the button.
<input type="radio">
Now is the question, is it possible to have a selected style or animation (Not a click/hover animation) for the last button that you clicked (Without obviously having to use radiobuttons/checkbox).
If so, how does one make this?
JSFiddle if you want to use the code that I used in the GIF
I haven't found a lot of articles about this, or maybe just haven't looked good enough, anyways, maybe you people know how to do this?
Include the JS in your page.
In your HTML, similarly to what you would do by adding the name and value attributes to your <input type="radio">s you add the data-name and data-value attributes to the elements you wish to behave as <input type="radio">s. If you want one to be selected by default add the attribute/value data-selected="true" to it.
Target the selected elements in CSS with the [data-radio-selected='true'] selector.
document.addEventListener('DOMContentLoaded', () => {
const radioGroups = {}
document.querySelectorAll('[data-radio-name]').forEach( el => {
const name = el.dataset.radioName;
const value = el.dataset.radioValue;
const selected = el.dataset.radioSelected === 'true';
// Register radio
radioGroups[name] = radioGroups[name] || {
radios: [],
selected: null
};
radioGroups[name].radios.push(el);
if ( selected && radioGroups[name].selected == null ) {
radioGroups[name].selected = value;
}
// attach listeners
el.addEventListener('click', () => {
radioGroups[name].radios.forEach( el => {
el.dataset.radioSelected = 'false';
})
el.dataset.radioSelected = 'true';
radioGroups[name].selected = value;
})
})
})
[data-radio-selected='true'] {
background: red;
}
<button data-radio-name="animals" data-radio-value="pig">
Pig
</button>
<button data-radio-name="animals" data-radio-value="cow">
Cow
</button>
<button data-radio-name="animals" data-radio-value="chicken">
Chicken
</button>
Just toggle a class with an onclick event:
btnState = false;
btn.addEventListener("click", () => {
btn.classList.toggle("selected");
btnState = !btnState;
});
In the CSS add:
.selected {
background-color: red;
}
And add an id="btn" to the button in the HTML.
any way that when I press a button it shows me a class and when I press another it removes the other class from the first button and so on with the other buttons?
Thank you for your help
function myFunction() {
document.getElementById("active1").classList.add('MyClass');
}
function myFunction2() {
document.getElementById("active").classList.add('MyClass');
}
function myFunction3() {
document.getElementById("active2").classList.add('MyClass');
}
.MyClass {
background-color: red;
color: #00ff1f;
}
<html>
<body>
<div id="active1" class="none"><button onclick="myFunction()">Try it</button></div>
<div id="active" class="none"><button onclick="myFunction2()">forobeta</button></div>
<div id="active2" class="none"><button onclick="myFunction3()">femax</button></div>
<button onclick="myFunction4()">forobeta</button>
</body>
</html>
Sorry if I thought your question was a spam attempt. It was not clear you wanted to add a class on a clicked button AND remove that same class on all the other buttons.
So.... Just forget about the inline onclick with multiple functions then. One eventListener can do the job for as many buttons you like.
Just use a data attribute to store the href to open and that event listener will do the rest.
let allBtns = document.querySelectorAll("button")
// For each button, register an event listener
allBtns.forEach(function(elem){
elem.addEventListener("click", function(e){
// On click, remove the MyClass on ALL buttons
allBtns.forEach(function(el){
el.classList.remove("MyClass");
});
// Add the class on clicked one
e.target.classList.add("MyClass");
// Now pass the data-href to your iframe
let theHREFtoOpen = e.target.getAttribute("data-href")
console.log(theHREFtoOpen)
//document.querySelector("#your-iframe").src = theHREFtoOpen
})
})
.MyClass {
background-color: red;
color: #00ff1f;
}
<div><button data-href="some href!!">Try it</button></div>
<div><button data-href="some other href!!">forobeta</button></div>
<div><button data-href="and another href!!">femax</button></div>
<button data-href="as you like and so on.">forobeta</button>
I did not understand everything in the question
but you can use
".classList.toggle('MyClass');" instead of ".classList.add('MyClass');"
to add the class when you press it and remove the same class if you press the same button again as shown in the code but if you want to make one button add class and another button remove the same class if exist
you can use this piece of code ".classList.add('MyClass');" to the button the add the class and ".classList.remove('MyClass');" to the button that remove the class
function myFunction() {
document.getElementById("myFrame").src = "https://www.youtube.com/embed/ElN_4vUvTPs";
document.getElementById("active1").classList.toggle('MyClass');
}
function myFunction2() {
document.getElementById("myFrame").src = "https://www.youtube.com/embed/PfrV_6yWbEg";
document.getElementById("active").classList.toggle('MyClass');
}
function myFunction3() {
document.getElementById("myFrame").src = "https://dood.to/e/pr9xvqpvhjxu";
document.getElementById("active2").classList.toggle('MyClass');
}
function myFunction4() {
document.getElementById("myFrame").src = "https://uqload.com/embed-swysx69drg1h.html";
}
.MyClass {
background-color: red;
color: #00ff1f;
}
<html>
<body>
<div id="active1" class="none"><button onclick="myFunction()">Try it</button></div>
<div id="active" class="none"><button onclick="myFunction2()">forobeta</button></div>
<div id="active2" class="none"><button onclick="myFunction3()">femax</button></div>
<button onclick="myFunction4()">forobeta</button>
<iframe id="myFrame" src="/default.asp" width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>
</body>
</html>
In order to add a class on a click event to a button, you could do something like this:
const btnAddClass = document.getElementById('btnAddClass');
btnAddClass.addEventListener('click', (e) => {
btnAddClass.classList.add('blue');
});
In order to remove a class, the code is quite similar. Instead of calling the add() method on the classList property of an element, we need to call the remove() function:
btnAddClass.classList.remove('blue');
A live example can be found here:
https://jsfiddle.net/dwome9yz/
If your ultimate goal is to make some sort of 'active' element be the only one with the class enabled from a list of buttons, you could do something along the lines of this, to get rid of all the 'active' elements first:
const removeActiveClass = () => {
const activeElements = document.getElementsByClassName('blue');
for (const activeElement of activeElements) {
activeElement.classList.remove('blue');
}
};
domElement.addEventListener('click', (e) => {
removeActiveClass(); // Call this first to remove the 'blue' class from all other elements
btnAddClass.classList.add('blue');
});
A live example can be found here:
https://jsfiddle.net/dpzLn1tj/
A simplified approach of the code posted above would be to use the same click event handler for all the buttons and only add the class to the button that was clicked using the target property of the event argument (Event.target) that is passed down during the click event and to remove the class for all the other elements:
const removeActiveClass = () => {
const activeElements = document.getElementsByClassName('blue');
for (const activeElement of activeElements) {
activeElement.classList.remove('blue');
}
};
const onClick = (e) => {
removeActiveClass();
e.target.classList.add('blue');
};
document.getElementById('btnAddClass').addEventListener('click', onClick);
document.getElementById('btnRemoveClass').addEventListener('click', onClick);
Live examples can be found here:
https://jsfiddle.net/dpzLn1tj/1/
https://jsfiddle.net/27c1n0wL/
I have a container with 2 button elements inside of them. Both buttons have the same class name but different attribute values (size).
I have wrapped the buttons in a forEach property and added a click event listener.
Once the event is executed, I am using setAttribute('active', '') on the selected button, but when the other is clicked, it should remove the attribute from the old event, and add it to the current one.
Current situation:
It sets an active attribute on both buttons, but doesn't remove the inactive ones.
Expected result:
The active attribute should be only enabled when I click on the selected button.
Here's a basic snippet:
const getButtons = document.querySelectorAll('.test');
getButtons.forEach(button => {
button.addEventListener('click', () => {
button.setAttribute('active', '')
console.log(button.getAttribute('size'))
});
})
<div class="flex">
<button class="test" size="10">Press Me 10</button>
<button class="test" size="20">Press Me 20</button>
</div>
You need to go deeper. :)
You can use forEach inside an forEach
getButtons.forEach(button => {
button.addEventListener('click', () => {
getButtons.forEach(b => {
//remove all active attributes
b.removeAttribute('active')
})
// add single active attribute
button.setAttribute('active', '')
console.log(button.getAttribute('size'))
});
})
But actually the best way is always native - using radio buttons may be the best solution, because in radio button group there can be only one active button
use jquery toggle()
const getButtons = document.querySelectorAll('.test');
getButtons.forEach(button => {
button.addEventListener('click', () => {
button.toggle("active", function() {
console.log(button.getAttribute('size'))
});
});
})
You can remove the active attribute from buttons before applying active to new button. :)
getButtons.forEach(button => {
button.addEventListener('click', (e) => {
document.querySelectorAll("button[active]").forEach(button => button.removeAttribute('active'))
button.setAttribute('active', '')
console.log(button.getAttribute('size'))
});
})
var btn = document.querySelectorAll('.button');
function test() {
alert('hello')
}
btn.addEventListener("click", test);
After clicking on the "button" - test function should be called, bit it's not.
'.button' will search for all elements with class named 'button'. If you are searching for button elements you should write: document.querySelectorAll('button')
Additionally querySelectorAll gives nodeList.
For this code:
<button id="myBtn">Try it</button>
<button id="myBtn2">Try it</button>
<script>
var btn = document.querySelectorAll('button');
console.log(btn);
</script>
return will be NodeList[button#myBtn, button#myBtn2], as you can see it is an array.
document.querySelectorAll would return the list of elements. You need
to apply the click event on individual elements.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
var btn = document.querySelectorAll('.button');
console.log(btn[0]);
function test() {
alert('hello')
}
btn[0].addEventListener("click", test);
<div class = 'button'>Button</div>
I have several buttons in my WinJS page.
<button id="btn1">
Button 1
</button>
<button id="btn2"">
button 2
</button>...
and javascript to add click event to clicked button:
(function () {
WinJS.UI.processAll().done(function () {
var showButton = document.querySelector("xxx");
showButton.addEventListener("click", function () {
});
});
})();
How do i determine what button is clicked and set value of "xxx" to id of that button (btn1, btn2 etc...)
If I understood you correctly, you want to identify the button (sender) when you have multiple buttons that are attached to a single event handler.
MSDN:
In JavaScript, Windows Runtime event arguments are represented as a
single event object. In the following example of an event handler
method, the ev parameter is an object that contains both the sender
(the target property) and the other event arguments. The event
arguments are the ones that are documented for each event.
So you need to define an argument for the event handler and use its target property.
Let's say you have the following HTML:
<div id="label1"/>
<div>
<button id="button1">Button1</button><br />
<button id="button2">Button2</button><br />
<button id="button3">Button3</button><br />
</div>
and attached a single event handler to all of the buttons:
var button1 = document.getElementById("button1");
button1.addEventListener("click", buttonClickHandler);
var button2 = document.getElementById("button2");
button2.addEventListener("click", buttonClickHandler);
var button3 = document.getElementById("button3");
button3.addEventListener("click", buttonClickHandler);
you can access to sender in this way:
function buttonClickHandler(eventInfo) {
var clickedButton = eventInfo.target;
var label1 = document.getElementById("label1");
label1.innerHTML = clickedButton.id.toString();
}
Here's a WinJS solution to get the buttons :
var buttons = WinJS.Utilities.query('button');
Then you can bind the event to the buttons click :
buttons.forEach(function (btn) {
btn.addEventListener("click", function () {
console.log('button ' + this.id + ' has been clicked.');
})
});
I am new to WinJS, so there is probably a prettier solution to replace the forEach.
Something like this should work. querySelector only returns the first match, so you need to use querySelectorAll (see docs).
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
var id = this.id;
// do stuff with "id"
});
}
You might also consider looking into jQuery as that can make things like this a little bit cleaner.