Jquery selector - how can I ensure this works? - javascript

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>

Related

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");

How do I get a currently visible (default hidden) slideToggle() .div to close when another is opened?

So I have close to what I would like to achieve, including having my slideToggle .divs close when I click anywhere off of the "link" divs (.click, .click2) with one glaring exception...
When I click "Link 1" it does what I'd like and displays .showup then if I click "Link 2" it also initially does what I'd like and displays .showup2 over .showup BUT I need .showup to close so that they aren't both open at the same time.
As you can see with my provided code this presents a problem bc with both "showup" divs already open if I then directly click "Link 1" again .showup remains hidden behind .showup2
Similarly, in the above example if I click "Link 2" first, .showup2 opens but when I then directly click "Link 1", .showup does not appear over .showup2
So ultimately I would like my slideToggle divs to hide when I click ANYWHERE outside of my "Link" divs (.click and .click2) - which it currently does - however that ANYWHERE should include my other script instructed "Link" divs!! And that is where I am stumped.
Here is code that demonstrates in a very simplified example :
HTML
<div class="click">Link 1</div> <div class="click2">Link 2</div>
<div class="showup">something I want to show</div>
<div class="showup2">something else I want to show</div>
SCRIPT
$(document).ready(function(){
$('.click').click(function(event){
event.stopPropagation();
$(".showup").slideToggle("fast");
});
});
$(document).on("click", function () {
$(".showup").hide();
});
$(document).ready(function(){
$('.click2').click(function(event){
event.stopPropagation();
$(".showup2").slideToggle("fast");
});
});
$(document).on("click", function () {
$(".showup2").hide();
});
CSS
body{margin:50px;}
.showup,
.showup2 { width:100%;height:100px; background:red; display:none; position: fixed;}
.click,
.click2 { cursor:pointer; display:inline-block; padding: 0 15px;}
Thanks so much for any help! Jorie
You could do with same class name of the button and boxes .data-target attr used for target the which element to toggling .
Updated
Toggle function with each button
Bold text toggle function added
$(document).ready(function() {
$('.click').click(function(event) {
event.stopPropagation();
if($(".showup").eq($(this).attr('data-target')).css('display') == 'block'){
$(".showup").eq($(this).attr('data-target')).slideUp();
$('.click').removeClass('bold')
}
else{
$(".showup").hide();
$('.click').removeClass('bold')
$(".showup").eq($(this).attr('data-target')).slideToggle("fast");
$(this).toggleClass('bold')
}
});
}).on('click',function(){
$(".showup").hide();
$('.click').removeClass('bold')
})
body {
margin: 50px;
}
.showup{
width: 100%;
height: 100px;
background: red;
display: none;
position: fixed;
}
.bold{
font-weight:bold;
}
.click{
cursor: pointer;
display: inline-block;
padding: 0 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click" data-target="0">Link 1</div>
<div class="click" data-target="1">Link 2</div>
<div class="showup">something I want to show</div>
<div class="showup">something else I want to show</div>

Javascript - show a button inside of a DIV when clicked (and hide all others)

I have a list of DIVS that have buttons inside. By default, all buttons are hidden. When I click within a DIV area, the current button inside of this clicked DIV are should show (class='.db') AND all previously clicked/shown buttons should be hidden (class='.dn'). In other words, at any time there should be only one button (currently clicked) shown and all other should be hidden.
I want to use vanilla Javascript and tried this below, but it won't work. I feel there is some small error but don't know where.. Note - the DIVS and buttons don't have their own unique IDs (they only have the same CSS (.posted) classes.
PS - maybe it'd be better not to add this onClick="t();" to each DIV and use an 'addEventListener' function, but this is way too much for me ; )
CSS:
.dn {display:none}
.db {display:block}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
HTML:
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
<div class="posted" onClick="t();">
<button class="dn">Reply</button>
</div>
JAVASCRIPT:
function t()
{
var x=document.getElementsByClassName("posted"),i,y=document.getElementsByTagName("button");
for(i=0;i<x.length;i++)
{
x[i].y[0].className="dn";
};
x.y[0].className='db';//make sure the currently clicked DIV shows this button (?)
}
You might want to read more about selector, how to select class, block level etc.
some link might be helpful:
CSS selector:
https://www.w3schools.com/cssref/css_selectors.asp
jQuery selector:
https://api.jquery.com/category/selectors/
Solution - Using jQuery:
$('.posted').on('click', function() {
//find all class called posted with child called dn, then hide them all
$('.posted .dn').hide();
//find this clicked div, find a child called dn and show it
$(this).find('.dn').show();
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
Solution - Pure js version:
//get list of div block with class="posted"
var divlist = Array.prototype.slice.call(document.getElementsByClassName('posted'));
//for each div
divlist.forEach(function(item) {
//add click event for this div
item.addEventListener("click", function() {
//hide all button first
divlist.forEach(function(el) {
el.getElementsByTagName('button')[0].classList.add('dn');
});
//show button of the div clicked
this.getElementsByTagName('button')[0].classList.remove('dn');
}, false);
});
.dn {
display: none
}
.db {
display: block
}
.posted {
height: 50px;
width: 100px;
background-color: green;
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="posted">
<button class="dn">Reply1</button>
</div>
<div class="posted">
<button class="dn">Reply2</button>
</div>
<div class="posted">
<button class="dn">Reply3</button>
</div>
You can do this with with plain JavaScript using Event Bubbling, querySelector and the element classList attribute like this.
Change your HTML to look like this:
<div class="posts">
<div class="posted">
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
<div class="posted" >
<button class="dn">Reply</button>
</div>
</div>
Then use JavaScript like this:
var posts = document.querySelector('.posts');
var allPosted = document.querySelectorAll('.posted');
//clicks bubble up into the posts DIV
posts.addEventListener('click', function(evt){
var divClickedIn = evt.target;
//hide all the buttons
allPosted.forEach(function(posted){
var postedBtn = posted.querySelector('button');
postedBtn.classList.remove('db');
});
// show the button in the clicked DIV
divClickedIn.querySelector('button').classList.add('db')
});
You can find a working example here: http://output.jsbin.com/saroyit
Here is very simple example using jQuery .siblings method:
$(function () {
$('.posted').click(function () {
$('button', this).show();
$(this).siblings().find('button').hide();
});
});
https://jsfiddle.net/3tg6o1q7/

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

How to remove and add class with if statement?

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..

Categories

Resources