Javascript onclick menu change background colors - javascript

I have my menu like this:
https://jsfiddle.net/23r4q610/
And my code to change the selected menu button like below:
$('#bluebutton').click(function () {
$('.testul li').removeClass('selectedred selectedpurple selectedgreen selectedorange');
$('#bluebutton').addClass('selectedblue');
});
$('#redbutton').click(function () {
$('.testul li').removeClass('selectedblue selectedpurple selectedgreen selectedorange');
$('#redbutton').addClass('selectedred');
});
$('#purplebutton').click(function () {
$('.testul li').removeClass('selectedblue selectedred selectedgreen selectedorange');
$('#purplebutton').addClass('selectedpurple');
});
$('#greenbutton').click(function () {
$('.testul li').removeClass('selectedblue selectedred selectedpurple selectedorange');
$('#greenbutton').addClass('selectedgreen');
});
$('#orangebutton').click(function () {
$('.testul li').removeClass('selectedblue selectedred selectedpurple selectedgreen ');
$('#orangebutton').addClass('selectedorange');
});
Ofcourse this is bad code since it could be written much shorter. Should I go about this using just numbers so I can do some foreach, or is there a better way to do this?

This can be condensed by adding a generic click event on all buttons by using [id*="button"]. Then grab the relevant color from the nested anchor.
$('[id*="button"]').click(function(){
$('.testul li').removeClass();
$(this).addClass('selected'+$('a',this).attr('class'));
});
or
$('li').click.../*this would be the same as above*/
fiddle

In this particular case, there doesn't appear to be a good reason to add and remove classes. Just change the background color instead of adding and removing a class to do so.
$(this).css("background-color", "red");

I would avoid hard-coding the color names into the HTML IDs. Rather use a CSS class name like "selected" and describe in your CSS what that should look like. Example:
<li id="home-button" class="color-button">Home
CSS:
#home-button.selected,
#home-button:hover {
background: -webkit-linear-gradient(#78b1ff, #4881dc);
}
JS:
$('.color-button').click(function () {
$(this).toggleClass("selected").siblings(".color-button").removeClass("selected");
}
This way color information (presentation) is separated from semantic information (like "home") and JS code is daramtically shorter.
Note: this is just an advice, I have not tested it but should give you a good point to start.

You can reduce the code to only 1 click binding. Where when an element is clicked, class from all the li's is removed and then on the current clicked li, selected class is added.
$(".testul > li").click(function(){
$('.testul li').removeClass('selectedred selectedpurple selectedgreen selectedorange selectedblue');
var color = $(this).attr("id").replace("button","");
$('#'+color+'button').addClass('selected'+color);
});
Here is the updated fiddle - https://jsfiddle.net/23r4q610/2/

Related

Add class then remove and replace class on click

I have a default class. When the icon has been clicked, the default class will be removed and replaced with the new one, then when the icon has been clicked again, then the old class will be added again, then the new class will be removed. It should be changed every time the icon is clicked. It's closed to .toggleClass(), but should show/hide and replace the class.
Here is my js code
var MenuIcon = $('.menu-icon-plus'),
MenuSidebar = $('.sidebar');
MenuIcon.click(function(){
if ($(MenuSidebar).hasClass('test')) { //existing class
$(MenuSidebar).removeClass('test');
} else {
$(MenuSidebar).addClass('test2'); // replacement of old class
}
Add the two classes to toggleClass("default special") to swap them:
$("button").on("click", function(){
$(this).toggleClass("default special");
});
.default{
background:lime;
font-size:2em;
}
.special{
background:gold;
/* I don't have font size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="default">TEST</button>
P.S: If you wanted to only change the background, than toggleClass("special") would suffice.
Or, again using only .toggleClass("special") you could set directly in CSS the reset styles, but that just complicates stuff. It clearly depends on the use case.
Try this. Replace the classes as per your requirement.
$(document).on('click', '.oldclass', function() {
$(this).removeClass('oldclass').addClass('newclass');
});
$(document).on('click', '.newclass', function() {
$(this).removeClass('newclass').addClass('oldclass');
});

How to change CSS pseudo-class element using JavaScript

I want to change this image using javascript:
dance:active { background-image: url("myImage.png") }
You can use
document.getElementById(element).style.backgroundImage = url(image);
to change
#element {background-image: url(image)}
I would like to change the image of when the element is active using javascript. Thanks!
I figured it out!
You can have multiple classes in your CSS :
element.dance1 { stuff }
element.dance1:active { active stuff }
element.dance2 { stuff 2 }
element.dance2:active { active stuff 2 }
and then change the class of the element in javascript:
document.getElementById(element).className = dance1/dance2
You can try using jQuery to achive what you want. dance: active is CSS Pseudo-classes. Learn more about Pseudo-class.
The demo change the div color when mouse down and switch the color back when mouse up. Leave comments if this is not what you want.
$("#dance").on("mousedown", function () {
$("#dance").css("background", "blue");
}).on("mouseup", function(){
$("#dance").css("background", "black");
});
https://jsfiddle.net/x_li/5nkvms8q/
and jQuery can also do the following
$('#damce:checked').val();

Alternate colors on click with jQuery

I'm sure there is a simple solution to this, and I'm sure this is a duplicate question, though I have been unable to solve my solution particularly because I don't really know how to phrase it in order to search for other questions/solutions, so I'm coming here hoping for some help.
Basically, I have spans with classes that assigns a background-color property, and inside those spans are words. I have three of these spans, and each time a user clicks on a span I want the class to change (thus changing the background color and inner text).
HTML:
<span class="alternate">
<span class="blue showing">Lorem</span>
<span class="green">Ipsum</span>
<span class="red">Dolor</span>
</span>
CSS:
.alternate span { display : none }
.alternate .showing { display : inline }
.blue { background : blue }
.green { background : green }
.red { background : red }
jQuery:
$(".alternate span").each(function() {
$(this).on("click", function() {
$(this).removeClass("showing");
$(this).next().addClass("showing");
});
});
This solution works great using $.next until I get to the third click, whereafter .showing is removed, and is not added since there are no more $.next options. How do I, after getting to the last-child, add .showing to the first-child and then start over? I have tried various options including if($(".alternate span:last-child").hasClass("showing")) { etc. etc. }, and I attempted to use an array and for loop though I failed to make it work.
Newb question, I know, but I can't seem to solve this so as a last resort I'm coming here.
try this:
$(".alternate span").each(function() {
$(this).on("click", function() {
$(this).removeClass("showing");
if($(this).is(":last-child"))
$(".alternate span:first-child").addClass("showing");
else
$(this).next().addClass("showing");
});
});
http://jsfiddle.net/NPx2x/
Check this, and also it performs faster. .next() returns undefined if no element found.
$(".alternate span").on("click", function() {
$(this).removeClass("showing");
var next = $(this).next();
next.length ? next.addClass("showing") : $("span.blue").addClass("showing");
});

Javascript Tab - Active Class

I am using the following js which works great for hiding and showing content when one of 5 tabs is clicked. Works great but my question is, how could i adjust the code so that when a tab's content is currently being displayed, the tab has an active class. The hover class works well and so does everything else besides the active class. Any help is hugely appreciated:
$(window).ready(function() {
$('#infotab').click(function() {
$(document).find('.tabcontent').hide();
$('.infotabcontent').show();
$(document).find('.top-nav2-menu li').removeClass('tabactive');
$('#infotab').addClass('tabactive');
$('#reviewtab').removeClass('tabactivelast');
});
$('#findingtab').click(function() {
$(document).find('.tabcontent').hide();
$('.findingtabcontent').show();
$(document).find('.top-nav2-menu li').removeClass('tabactive');
$('#findingtab').addClass('tabactive');
$('#reviewtab').removeClass('tabactivelast');
document.getElementById('frame1').contentDocument.location.reload(true);
});
$('#streetviewtab').click(function() {
$(document).find('.tabcontent').hide();
$('.streetviewtabcontent').show();
$(document).find('.top-nav2-menu li').removeClass('tabactive');
$('#streetviewtab').addClass('tabactive');
$('#reviewtab').removeClass('tabactivelast');
document.getElementById('frame2').contentDocument.location.reload(true);
});
$('#videotab').click(function() {
$(document).find('.tabcontent').hide();
$('.videotabcontent').show();
$(document).find('.top-nav2-menu li').removeClass('tabactive');
$('#videotab').addClass('tabactive');
$('#reviewtab').removeClass('tabactivelast');
});
$('#reviewtab').click(function() {
$(document).find('.tabcontent').hide();
$('.reviewtabcontent').show();
$(document).find('.top-nav2-menu li').removeClass('tabactive');
$('#reviewtab').addClass('tabactivelast');
});
});
Your code is a pain ...
$(window).ready(function() { should be $(function() {
which is a shorthand for $(document).ready(function(){
In your HTML assign a class class="tab" to all your id="***tab" elements
Cache your elements collections $('.tabcontent') and $('.top-nav2-menu li')
use the $(this) selector
Than this is all you need:
$(function(){ // DOM is now ready
// Cache your selectors
var $tabCont = $(".tabcontent"),
$topNavLi = $(".top-nav-menu li"),
$tabRev = $('#reviewtab');
$('.tab').click(function() {
var myId = this.id;
if(myId=="findingtab"){
$('#frame1')[0].contentDocument.location.reload(true);
}
if(myId=="streetviewtab"){
$('#frame2')[0].contentDocument.location.reload(true);
}
$tabCont.hide();
$("."+ myId +"content").show();
$(this).addClass('tabactive').siblings().removeClass('tabactive');
$tabRev.removeClass('tabactivelast');
if(myId=="reviewtab"){
$(this).addClass('tabactivelast');
}
});
});
With something like:
function deactivateAllTabs(){
$('#infotab, #findingtab, #streetviewtab, #videotab, #reviewtab').removeClass('tabactive');
}
Then, prior to adding your tabactive class you'd call this method:
So, for example, instead of:
$('#infotab').addClass('tabactive');
do this:
deactivateAllTabs();
$('#infotab').addClass('tabactive');
repeate this for all your click handlerss
This way, the active tab will always have a tabactive class
I don't know your DOM structure, since you didn't post it, but I'm assuming that every tab has an identical class, "tabcontent", from what you've posted. If so, you could do something like this inside your function:
$('.tabcontent').removeClass('.tabactive'); // removes class from all tabs
$('#sometab').addClass('.tabactive'); // adds class to specific tab
Then you could show or hide using just some CSS, like this:
.tabcontent { display: none; }
.tabactive { display: block; }
IMHO you'd also be better off using a single function for all of your tabs so they get the same treatment. Easier to maintain. e.g. Give each tab bar item that you click on to see the tab a data attribute with the id of the div you want to display, and you could expand on something like this (untested but hopefully you get the gist):
$('.tab').click(function() {
$('.tabcontent').removeClass('.tabactive');
$($(this).data('tabcontent')).addClass('.tabactive');
});

Change Toggle(); from Display:none to Visibility:hidden

This code is working successfully on the project that I am working on. The problem with this is that the elements that this code affects are positioned absolutely. When .field-name-field-pin-point it clicked the element .group dealer is hidden, but the .field-name-field-pin-point moves off of the page. Ideally, I would like the visibility to be set at none upon page load, but it would probably be easier to do that part in CSS. Here is what I am currently using:
jQuery(document).ready(function () {
jQuery('.node-202 .field-name-field-pin-point').click(function() {
jQuery(this).siblings('.group-dealer').toggle();
});
});
There will be more nodes that will be positioned differently so the full class name I provided is necessary. The markup (generally speaking) is as follows:
<div class="node-202">
<div class="group-dealer">...</div>
<div class="field-name-field-pin-point">...</div>
</div>
I am basically creating points on a map that when clicked, bring up a small window with more information about that location.
Here is a reference to my last post if you are looking for more information: Toggle Class Visibility by Clicking on another Class
I suggest your best approach is to add a css rule and just toggle a class on the elements
CSS
.group-dealer.hidden{ visibility:hidden}
JS
jQuery('.node-202 .field-name-field-pin-point').click(function() {
jQuery(this).siblings('.group-dealer').addClass('hidden');/* use toggleClass if more appropriate*/
})
Just toggle the visibility then
jQuery(document).ready(function () {
jQuery('.node-202 .field-name-field-pin-point').click(function() {
jQuery(this).siblings('.group-dealer').css('visibility', function(_,vis) {
return vis == 'hidden' ? 'visible' : 'hidden';
});
});
});
Try:
$('.node-202 .field-name-field-pin-point').click(function () {
if ($(this).siblings().css('visibility') == 'visible') {
$(this).siblings().css('visibility', 'hidden');
} else {
$(this).siblings().css('visibility', 'visible');
}
});
DEMO here.

Categories