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/
Related
Basically what the title says this is the code that I've tried but it doesn't work:
<div id="box" onclick="doSmt(var1, bar2)">
if (condition){
box.removeEventListener("click" , doSmt)}
I think it's better if you remove the onclick event instead of that attempt
//onclick function
function doSmt(){
console.log("something");
}
//remove onclick event, this will be inside your if condition
document.getElementById('box').removeAttribute("onclick");
<div id="box" onclick="doSmt()"> div</div>
What what I read at MDN for removeEventListener you can't remove an event listener that is part of the HTML attribute. So there's two options:
Add the event listener on page load
onClickHandler = () => doSmt(var1, var2);
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('box').addEventListener('click', onClickHandler);
});
// and later
if (condition) {
document.getElementById('box').removeEventListener('click', onClickHandler)
Or if you can't modify the HTML you could modify doSMT to watch for a disabled bit.
let disableBox = false;
function doSmt() {
if (disableBox) return;
// ...
}
if (condition) {
disableBox = true;
}
Or
it can be removed by first accessing the element and then setting the attribute to null
<div id="myDiv" onclick="handleClick()">Click me</div>
<script>
function handleClick() {
alert("Div was clicked!");
}
// Remove the onclick event from the div
const div = document.getElementById("myDiv");
div.onclick = null;
</script>
I want to be able to click on an element and then depending on whether it has a specific class name, do something.
Here is what I have so far:
<div class="my-class" onclick="myFunction()"/>
function myFunction() {
if (element.classList.contains("my-class")) {
//do something
}
}
where am I going wrong?
You need to pass the click event then get the target element which in this case is the clicked element.
function myFunction(event) {
if (event.target.classList.contains("my-class")) {
alert("I Do things becuase i have (my-class)")
}
}
<button class="my-class" onclick="myFunction(event)">Click me</button>
<br/>
<br/>
<br/>
<br/>
<button onclick="myFunction(event)">I Do nothing</button>
As #collapsar mentioned in comment, element is't set. I recommand you to use addEventListener and event.target.
document.getElementById("your-element").addEventListener("click", () =>{
if (event.target.classList.contains("my-class")) {
console.log("your-element has \"my-class\" class")
}
})
<div id="your-element" class="my-class">Click</div>
When the HTML element rendered statically you should consider two things:
Wait for the DOM ready event in order to make modifications on the element.
Attach the event dynamically, making sure that you bind the event handler to new elements after adding them to the DOM.
HTML
<div class="my-class" />
Javascript
function myFunction(event) {
var element = event.target;
if (element.classList.contains("my-class")) {
//do something
}
}
document.addEventListener("DOMContentLoaded", function(event) {
// DOM is ready
const elements = document.getElementsByClassName("my-class");
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction);
}
});
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!')
}
Hello could someone help me? I'm having trouble transforming this part of my code to JS:
$(".custom-select-trigger").on("click", function() {
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
$(this).parents(".custom-select").toggleClass("opened");
event.stopPropagation();
});
I have it so far:
const customSelectTrigger = document.querySelector(".custom-select-trigger");
const customSelect = document.querySelector(".custom-select");
function showOptions(e) {
e.preventDefault();
customSelect.classList.toggle("opened");
e.stopPropagation();
}
but I'm not able to do this part for javascript:
$('html').one('click',function() {
$(".custom-select").removeClass("opened");
});
Here is working code for to remove class opened from your custom select when you press anywhere in the DOM.
You need to use JS addEventListener and click function to do this.
To remove class from an element we can use .remove function and getting the classList of your element by querySelector which will .custom-select
Edit: If you just want to use the click function once only per DOM load. Then setting setting the args { once: true } will only invoke the function once.
I have recreated your example and its working.
Run snippet below.
//Getting HTML element
const htmlElement = document.querySelector("html");
//Getting element where to remove the class from
const customSelect = document.querySelector(".custom-select");
//Adding eventlistener to remove class opened from classList
htmlElement.addEventListener("click", function(e) {
customSelect.classList.remove("opened");
console.log('Class Removed')
e.preventDefault();
},{ once: true });
.opened {
background-color: red;
}
<html>
<h3>
Click anywhere on the DOM to remove class from Custom select
</h3>
<div class="custom-select opened">
My Custom Select
</div>
</html>
I would like to replace the default action of an click event for all anchors in a webpage.
When I use this piece of code:
<html> <head> <script>
var list=document.getElementsByTagName("a");
var isChecked = false;
function load () {
for (i=0; i<list.length; i++)
{
var old = (list[i].onclick) ? list[i].onclick : function () {};
list[i].onclick = function () {
if( !isChecked)
{
test();
old();
}
else
old();
};
}
}
function test() {
alert("new action");
isChecked = true;
}
</script> </head>
<body onload="load();">
<a id="nr_1" onClick="alert('test');"> Anchor 1 </A>
<a id="nr_2" onClick="alert('test2');"> Anchor 2 </A>
</body> </html>
When I click an anchor I get the alert out of the test function and then the default function of the second anchor (even when I click the first anchor). When I then again click one of the two anchors I always get the Alert from the second anchor.
How do I put the original onclick functions back for each anchor element? When someone has an solution in jquery I would be glad as well.
EDIT
I was succesfull using this code:
function load()
{
$('a').attr('disabled', 'disabled');
$('a').click(function(e){
if($(this).attr('disabled'))
{
alert("new");
e.preventDefault();
$('a').removeAttr("disabled");
this.click();
}
});
}
On loading of the page this function is called giving all anchor elements a "disabled" attribute. After clicking the element the e.preventDefault() function disables the inline onclick function. Then I remove the "disabled" attribute and call the click function of the element again. because now the element doesn't have a "disabled" attribute only the default function is performed. I'm still open for "more elegant" solutions to this problem, but for now I'm a happy camper!
If you use jQuery you can combine a one-time handler with a persistent handler:
Documentation for .one() and .on()
Working Example: http://jsfiddle.net/Q8gmN/
Sample HTML:
<input type="button" id="click" value="click" />
Sample JavaScript:
button.one('click', function () {
console.log('one time function fired');
});
button.on('click', function () {
console.log('persistent function fired');
});