How to remove and add class with if statement? - javascript

I am trying to have the classes change depending on what is clicked from the two headings.
If heading one is clicked, I want the font color to change to red and have it underlined with red, which in the class it currently does with a bottom border. If the other heading is clicked then I want that heading to take on the red characteristics. The one that is not clicked will just stay grey according to the no highlight class.
Here is the JSFiddle: http://jsfiddle.net/7ok991am/1/ I give an example look also of what I am trying to accomplish.
HTML:
<div id="page_headings">
<h2 class="no_highlight">Heading One</h2>
<h2 class="no_highlight">Heading Two</h2>
</div>
CSS:
#page_headings{
overflow: hidden;
margin-bottom: 32px;
}
#page_headings h2{
float: left;
margin-right:24px;
font-size: 14px;
cursor:pointer;
}
#page_headings h2:hover{
font-weight: bold;
}
.red_highlight{
color:red;
border-bottom: 1px solid red;
}
.no_highlight{
color:#898989;
}
JS:
$('#page_headings').on('click', function(){
if($('#page_headings h2').hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$('#page_headings h2').addClass('no_highlight');
};
});

Building on #RDrazard I think you want them to switch between the two correct?
http://jsfiddle.net/7ok991am/3/
$('#page_headings h2').on('click', function(){
if($(this).hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$(this).addClass('no_highlight');
}
$(this).siblings('h2').addClass('no_highlight');
});

JSFiddle: Link
First off, add a border-bottom property with none to the no highlight class to ensure that it looks just the same before the click.
Next, you want to the click event associated with the h2 elements, so it should be $('#page_headings h2')
Use this to impact the h2 we're clicking on.

Try this code
$('#page_headings h2').on('click', function(){
if($(this).hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$(this).addClass('no_highlight').removeClass('red_highlight');
}
});

Check this fiddle
JS
$('.no_highlight').on('click', function(){
$(this).parent().find('.no_highlight').css('border-bottom','none');
$(this).css('border-bottom','1px solid red');
});
The above method changes the border of the currently clicked headinh which i think is what you want.
AND
if you want addClass() and removeClass(), then see this fiddle
JS
$('.no_highlight').on('click', function(){
$(this).parent().find('.no_highlight').removeClass('red_highlight');
$(this).addClass('red_highlight');
});
This method adds a red_highlight class to the active link and removes the red_highlight when not active.
Please try it..

Related

Jquery selector - how can I ensure this works?

I have some buttons, labelled logo1 - logo15 respectively.
There is another button called 'lets-go' that fires a function based on these buttons being selected - when you click a logo the class 'active'.
When there is no logo selected, I would like this button to not be in the DOM - and be hidden. At the moment, the 'active' class for the button brings it's opacity to 1.
I have this jquery statement at the moment.
if (!$('.logo1, .logo2, .logo3, .logo4, .logo5, .logo6, .logo7, .logo8, .logo9, .logo10, .logo11, .logo12, .logo13, .logo14, .logo15').hasClass("active")) {
$('#lets-go').removeClass('active')};
But it's not working.
This is an example of one of my logoX buttons:
$('.logo15').on('click', function(e) {
$('.logo15').toggleClass("active");
$('#b15').toggleClass('alive');
$('#b15').toggleClass('zoomTarget');
$('#b15').toggleClass('dead');
$('#lets-go').addClass('active');
$('#popoutLetsGo').addClass('expand');
$('.instructions-arrow-2').addClass('hide')
});
On click, they apply the class of 'active' to let's go. But it doesn't remove it, ever. Just if you click any of the 15 buttons a new button appears, but if you deselect the button it's still there - and then the next screen is blank.
Can you see why it's not?
I am basically looking for: If none of these classes have the class of active, then make sure this id doesn't have the class of active either.
Consider the following:
if (!$("[class*='logo']").hasClass("active")) {
$('#lets-go').removeClass('active')};
}
This looks at the Class attribute for a item starting with "logo", so .logo3 would be one of those elements. But you may want to test each one.
$("[class*='logo']").each(function(i, el){
if(!$(el).hasClass("active")){
$('#lets-go').removeClass('active')};
}
});
See More:
https://api.jquery.com/attribute-contains-selector/
https://api.jquery.com/each/#each-function
You can also use simplified classes to help group selectors. Consider the following.
$(function() {
$(".logo").click(function() {
$(".logo.active").removeClass("active");
$(this).addClass("active");
$("#letsgo").prop("disabled", false);
});
$("#letsgo").prop("disabled", true);
})
.logo {
padding: .4em;
border: 1px solid black;
border-radius: 3px;
margin: 3px;
background: #eee;
color: #999;
}
.active {
background: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Make a Selection</p>
<div class="logo item-1">Logo 1</div>
<div class="logo item-2">Logo 2</div>
<div class="logo item-3">Logo 3</div>
<div class="logo item-4">Logo 4</div>
<div class="logo item-5">Logo 5</div>
<button id="letsgo">Let's Go!</button>

Changing classes with jQuery but the element doesn't change color?

I was in the middle of self studying HTML, CSS and JavaScript when at my job, an interviewer came to me and suggested to study jQuery as it was the “standard” now days.
So I decided to do that and started to migrate my own web page project for a future game I'm going to make, to jQuery, and it is pretty easy to understand so far and made me compress 150 or so lines of javaScript into 70 (more or less).
Now I am trying to add a class to a button when clicked using jQuery,
for that I am using:
$(this).addClass("buttonActive");
In CSS, the button is:
.menu .buttonActive {
background-color: #222629;
}
When clicking the button, the buttin does change color, and that is perfect, but I wanted to make so that the color changes to the original one once I click another button, but it is not working.
For that I am using:
$("#buttonClicked").removeClass("buttonActive");
I also tried adding another class together when removing the buttonActive but it didn't work.
$("#buttonClicked").removeClass("buttonActive").addClass("buttonNotActive");
.buttonNotActive {
background-color: #10394E;
}
Try this example:
First remove buttonActive class from all buttons except the clicked one
Toggle buttonActive class for the clicked button
$(".myButton").click(function() {
$(".myButton").not($(this)).removeClass('buttonActive');
$(this).toggleClass("buttonActive");
})
.menu .buttonActive {
background-color: #222629;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
<button class="myButton">My button</button>
<button class="myButton">My button</button>
<button class="myButton">My button</button>
</div>
I didn't understand well. Like this?
$("#buttonClicked").click(function(){
$(this).addClass("buttonActive");
})
$("#change").click(function(){
$("#buttonClicked").removeClass("buttonActive");
})
.menu .buttonActive {
background-color: #222629;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
<button id="buttonClicked">Button</button>
<button id="change">Change</button>
</div>
Add a class to each of the elements that would be clicked. Use that class for the click function. When that element is clicked, remove the active class from the elements, and apply it to the element that was clicked.
In this example when you click on one of the elements its background will change to red. If you click on another element, it returns to its original color.
$( ".menu-item" ).click(function() {
$(".menu-item").removeClass("buttonActive");
$(this).addClass("buttonActive");
});
.item-1 {
background-color: green;
}
.item-2 {
background-color: orange;
}
.item-3 {
background-color: purple;
}
.menu p {
color: #fff;
}
.buttonActive {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div class="menu">
<p class="item-1 menu-item">Item 1</p>
<p class="item-2 menu-item">Item 2</p>
<p class="item-3 menu-item">Item 3</p>
</div>
Thanks to everyone who answered.
Thanks to the ideas, I thought of selecting all buttons from my page and removing the buttonActive class
$(:button).removeClass("buttonActive");
$(this).addClass("buttonActive");

AngularJS / CSS - show/hide element on mouseover

This code only applies the .current class to my span, but the span is not hidden in the first place. I want it to be hidden, then on hover + ctrl - displayed, and on mouseleave - hidden again. How can I achieve that?
html:
<div class="portlet-titlebar" ng-mouseover="hoverIn()">
<span class="remove" class="hidden">
<clr-icon shape="times-circle" class="is-warning" size="16"></clr-icon>
</span>
</div>
directive:
scope.hoverIn = function(){
var res = document.getElementsByClassName('remove');
var result = angular.element(res);
if(event.ctrlKey){
result.removeClass('hidden');
result.addClass('current');
}
}
less:
.hidden{
display:none;
}
.current{
display: block;
border: 1px solid red;
}
Based on the question, this is my solution, on hovering the ng-mouseover($event) will track the hovering, then a if condition will check if ctrl key is pressed, you need to pass the $event through the function. Then on mouse leave you need the ng-mouseleave directive to detect this and call another function to hide it again.
Now coming to your question, if you want the span to be intially hidden then just add the class hidden to the span initially.
I have added the below CSS class so that the container does not become very small, to facilitate easy hovering.
.portlet-titlebar {
border: 1px solid black;
min-height: 50px;
}
Here is a working demo, let me know if there are any issues, we can sort it out.
JSFiddle Demo

How to use JavaScript to Alter CSS for Multiple Elements

I am trying to use JavaScript to change the background color of an element after being selected, and also to make sure that only one element at a time has the particular background color. Once the user selects on a different element I would like the previous element that was selected to be replaced by a different background color. Currently I am only able to toggle individual elements by selecting on EACH element. I need to be able to select on an element and apply the new background color, then have JavaScript change the background color of the previously active element to a different color (one less click).
What I am trying to do is very similar to modern navbars or list items where only one element at a time is “active” and has a background color that is different than the other elements in the same div, row, etc.
Notes about my work I am utilizing bootstrap and have no desire to use jQuery for this particular project.
CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h4 {
border: 1px solid black;
border-radius: 8px;
padding: 10px 2px 10px 2px;
margin: 20px 20px 0px 20px;
background-color: #F0F0F0;
border-color: #F8F8F8;
color: #505050;
cursor: pointer;
}
.active {
background-color: #99E6FF;
}
</style>
</head>
</html>
HTML:
<div id="pTwoRowOne">
<div class="row">
<div class="col-md-4 row row-centered">
<h4 id="techBio" class="test">Biology</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techCart" class="test">Cartography</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techChem" class="test">Chemistry</h4>
</div>
</div>
</div>
JavaScript:
document.getElementById("techBio").onclick=function() {
document.getElementById("techBio").classList.toggle('active');
}
document.getElementById("techCart").onclick=function() {
document.getElementById("techCart").classList.toggle('active');
}
document.getElementById("techChem").onclick=function() {
document.getElementById("techChem").classList.toggle('active');
}
An example can be seen here: http://jsbin.com/fugogarove/1/edit?html,css,js,output
If clarification is needed let me know.
Yup, pretty straightforward.
Assumptions
You're not trying to support IE8, since you're using classList
You're okay with housing your elements as variables as opposed to repeatedly querying the DOM.
Example
JSBin
Code
I rewrote your JavaScript to make it a little bit cleaner and to DRY it up a bit:
var techs = [].slice.call(document.querySelectorAll('#pTwoRowOne h4'));
function set_active(event) {
techs.forEach(function(tech){
if (event.target == tech) { return; }
tech.classList.remove('active');
});
event.target.classList.toggle('active');
}
techs.forEach(function(item) {
item.addEventListener('click', set_active);
});
Some explanation
[].slice.call(document.querySelectorAll('#pTwoRowOne h4')); – We're using this to change the output from a NodeList to an Array. This allows us to use forEach later. querySelectorAll returns a NodeList that contains all elements matching the CSS selector. You can probably replace that with a better CSS selector depending on your environment.
addEventListener is a much nicer way than the iterative add via onclick += to bind an event listener. It's also the recommended way (as far as I know) in ECMA5 and later.
By setting the element queries as variables, you'll be able to keep the reference in memory instead of polling the DOM every time to alter elements. That'll make your JavaScript marginally faster, and it's again just a nicer, cleaner version of the code which it produces.
updates
I reworked the JS to make more sense.
Assuming you only ever have one active element, you can find it using document.querySelector() - if you can have multiples you can use document.querySelectorAll() and iterate through them.
Simple case:
function activate(event) {
var active=document.querySelector('.active');
// activate the clicked element (even if it was already active)
event.target.classList.add('active');
// deactivate the previously-active element (even if it was the clicked one => toggle)
if (active) active.classList.remove('active');
}
document.getElementById("techBio").addEventListener("click",activate);
document.getElementById("techCart").addEventListener("click",activate);
document.getElementById("techChem").addEventListener("click",activate);
h4 {
border: 1px solid black;
border-radius: 8px;
padding: 10px 2px 10px 2px;
margin: 20px 20px 0px 20px;
background-color: #F0F0F0;
border-color: #F8F8F8;
color: #505050;
cursor: pointer;
}
.active {
background-color: #99E6FF;
}
<div id="pTwoRowOne">
<div class="row">
<div class="col-md-4 row row-centered">
<h4 id="techBio" class="test">Biology</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techCart" class="test">Cartography</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techChem" class="test">Chemistry</h4>
</div>
</div>
</div>
Another similar yet simpler way to do it: jsBin ;)
var H4 = document.getElementsByClassName("test"), act;
[].forEach.call(H4, function(el){
el.addEventListener("click", function(){
if(act) act.classList.remove("active");
return (this.classList.toggle("active"), act=this);
});
});
You can do something like this:
[].slice.call(document.querySelectorAll(".test")).forEach(function(element) {
element.addEventListener('click', function(event) {
if (activeElement = document.querySelector(".test.active")) {
activeElement.classList.remove("active");
};
event.target.classList.add('active');
});
});
Basically, first we remove the active class from the active element, then we add it to the target.
JSBin

Targeting Next Div Element in Jquery

Here is the HTML
<a style="border: medium none; display: block;" class="agendaNav" href="#"><img class="rightArrow" src="/images/arrowdown.png"> WEEK AT A GLANCE</a>
<div class="agendaDay">
Content In Here
</div>
The Same link / class is repeated several times and I use the following JQuery:
$('.agendaNav').click(function(event){
event.preventDefault();
if($(this).find('.rightArrow').attr('src')=='/images/arrowdown.png'){
$(this).find('.rightArrow').attr('src', '/images/arrowright.png');
$(this).attr('style', 'border-bottom: 1px solid #fff; display: block;');
} else {
$(this).find('.rightArrow').attr('src', '/images/arrowdown.png');
$(this).attr('style', 'border: none; display: block;');
}
$('.agendaDay').toggle('fast');
});
If you take a look here:
http://icuc2011.com/agenda
You'll see that it changes every class of agendaDay which makes sense, but I only want to change the one directly after the 'a' tag that was clicked, I tried this:
$(this).next('.agendaDay').toggle('fast');
But then the arrow changes but the div of class agenda day doesn't change at all, what am I doing wrong?
Your example doesn't match your actual code. In your code the link is inside a p tag. The div is a sibling following this p tag. If this is consistently the way it works, then you want:
$(this).parent().next('.agendaDay').toggle();

Categories

Resources