Given a script that toggles between two classes, I'm also adding an active state to the currently selected link to set an underline to show active state. However, when clicking the link continuously, it keeps adding the active class, rather than toggling the class on and off. How can I get the active state to show when the link is clicked, and switch off and apply to the other link when the other link is clicked?
JS
const Terms = {
bindEvents () {
this.enTrigger.addEventListener('click', (e) => {
this.langToggle(this.englishContent)
this.enTrigger.classList.add('active')
this.frTrigger.classList.remove('active')
})
this.frTrigger.addEventListener('click', (e) => {
this.langToggle(this.frenchContent)
this.frTrigger.classList.add('active')
this.enTrigger.classList.remove('active')
})
},
init () {
this.englishContent = document.getElementById('english-terms')
this.frenchContent = document.getElementById('french-terms')
this.enTrigger = document.getElementById('en')
this.frTrigger = document.getElementById('fr')
this.bindEvents()
},
langToggle (id) {
this.englishContent.style.display = 'none'
this.frenchContent.style.display = 'none'
id.style.display = 'block'
}
}
document.addEventListener('DOMContentLoaded', () => {
Terms.init()
})
HTML
<div class="terms-nav">
<a id="en">English</a><a id="fr">French</a>
</div>
You could try using something like this to toggle between the two classes. So when you click on one element, it adds the class to itself but removes it from the other one.
JS Fiddle
var english = document.getElementById('en');
var french = document.getElementById('fr');
english.addEventListener('click', function(){
this.classList.add('active');
french.classList.remove('active');
});
french.addEventListener('click', function(){
this.classList.add('active');
english.classList.remove('active');
});
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.
I would like to change Link (A) color in the Navbar upon clicking and also if I navigate to another Link (B) color should return to default for Link(A).
links.forEach( a=>{ //Its Color Changes But I Want All The Others To Be In Default Color
a.onclick = () => {
a.classList.add("active");
}
})
Add event to each element then on click on link perform add/remove of class.
var navElements = document.querySelectorAll('a');
//looping through each anchor element
navElements.forEach(function(element){
//adding click event on each anchor element
element.addEventListener('click',function(e){
//stop default behaviour
e.preventDefault();
//select current active element
let active = document.querySelector('.selected');
active?.classList.remove('selected'); //remove class
this.classList.add('selected'); //add class to current click element
});
});
links.forEach(a=> {
a.onclick = () => {
links.forEach(a=>a.classList.remove('active'));
a.classList.add("active");
}
})
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'))
});
})
So I have a button that is a div class, lets call it "login-button-arrow".
I want to set up a javascript method, so when this div gets clicked on, a little javascript box can pop up.
How do I go about doing this?
I have tried something like this:
login-button-arrow.onclick{alert('xyz')}
but I guess it does not work like that.
// Get #popup element:
const popup = document.querySelector("#popup");
// Function to toggle popup (toggles .active)
const togglePopup = () => {
console.log( "xyz" );
popup.classList.toggle("active");
};
// Get buttons elements from DOM
const buttons = document.querySelectorAll('.login-button-arrow');
// Assign event listener with callback to every button:
buttons.forEach((btn) => {
btn.addEventListener("click", togglePopup);
});
$('.login-button-arrow').on('click', function() { alert('xyz'); });
var login-button-arrows = document.getElementsByClassName('login-button-arrow');
login-button-arrows.forEach(function(obj){
obj.addEventListener('click', function(){
alert('xyz');
});
});
using Jquery :
$('#login-button-arrow').on('click', function(){ alert('xyz'); });
I have the javascript/html below. When the user clicks on 'heart' or 'coal' it switches to the opposite. However, it only works for 1 click. If I click on 'heart' once, it turns into 'coal'...but if I click on 'coal' now, it doesn't turn into 'heart' again. Any idea on how to fix this?
<script>
$(document).ready(function(){
$('.like').click(function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
console.log('liked');
return false;
})
$('.unlike').click(function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
console.log('unliked');
return false;
})
})
</script>
<div>
<a href = "#" class = 'unlike'>
<div class = "heart"></div>
</a>
</div>
Use
$('body').on('click', '.like', function () {
});
The problem you are facing is because you are adding dynamically an element (by destroying and recreating it), and the new element have no event click handler bound to it.
The solution is the use of event delegation, you can use jQuery on.
Another solution is instead of create again and again the clicked element, add a generic class, and in its click change the inner HTML and switch the like/unlike classes.
Code:
<div> <a href="#" class='handler unlike'>
<div class = "heart">aa</div>
</a></div>
JS:
$(document).ready(function () {
$('.handler').click(function (e) {
if ($(this).hasClass('like')) {
$(this).html("<div class = 'heart'>aa</div>");
} else {
$(this).html("<div class = 'coal'>bb</div>");
}
$(this).toggleClass('unlike');
$(this).toggleClass('like');
return false;
})
})
Demo: http://jsfiddle.net/At3D9/
#meavo is correct.
Here is a sample jsfiddle with a code sample similar to what you posted.
http://jsfiddle.net/Q2pDG/
$(document).on("click", '.like', function (e) {
$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
return false;
});
$(document).on("click", '.unlike', function (e) {
$(this).parent().html("<a href = '#' class = 'like'><div class = 'coal'></div></a>");
return false;
});