Alternate colors on click with jQuery - javascript

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

Related

JavaScript/jQuery code optimization

I'm learning JavaScript and jQuery and currently I'm dealing with following code:
$("#hrefBlur0").hover(function() {
$("#imgBlur0").toggleClass("blur frame");
});
$("#hrefBlur1").hover(function() {
$("#imgBlur1").toggleClass("blur frame");
});
$("#hrefBlur2").hover(function() {
$("#imgBlur2").toggleClass("blur frame");
});
$("#hrefBlur3").hover(function() {
$("#imgBlur3").toggleClass("blur frame");
});
$("#hrefBlur4").hover(function() {
$("#imgBlur4").toggleClass("blur frame");
});
$("#hrefBlur5").hover(function() {
$("#imgBlur5").toggleClass("blur frame");
});
$("#hrefBlur6").hover(function() {
$("#imgBlur6").toggleClass("blur frame");
});
$("#hrefBlur7").hover(function() {
$("#imgBlur7").toggleClass("blur frame");
});
The code is supposed to remove blur effect from an image while I hoover a cursor on a href link on the website. I'm wondering if I can do it faster, with fewer lines of code.
I tried:
for (var i = 0; i < 8; i++) {
$("#hrefBlur" + i).hover(function() {
$("#imgBlur" + i).toggleClass("blur frame");
});
}
But that code doesn't work.
Here's the JS fiddle: link
You can set a class to the elements and select that class, for example let's say you want to use "blurMeContainer" for the container, you can do something like this:
$(".blurMeContainer").hover(function(el){
$(this).find("img").toggleClass("blur frame");
});
The trick is that you must be aware that jQuery applies the events to the element, so inside the events function, the "this" accessor is the element involved in the event, than you can use the $ function in the selector in order to have his corrispective jQuery element, and then you can use "find" method to find any img tag inside the jQuery element. Obviously this could work only if you have a single image in the container, if you need to identify only one image in a set of images inside a single container, assign a class to that image (IE: "blurMe") and change the code in this way:
$(".blurMeContainer").hover(function(el){
$(this).find(".blurMe").toggleClass("blur frame");
});
Use attributeStartsWith selector , that Selects elements that have the specified attribute with a value beginning exactly with a given string:
$('a[id^="hrefBlur"]').hover(function() {
$(this).find('img').toggleClass("blur frame");
});
Here's working fiddle
Although doing what your after can be done with JQuery. I personally think it's the wrong tool for the Job.
CSS, will do all this for you, in a much simpler way. No Javascript needed. With the added benefit of the browser optimisations.
.blurme {
filter: blur(3px);
cursor: pointer;
transition: color 2s, filter 1s;
}
.blurme:hover {
filter: none;
color: red;
font-weight: bold;
}
<span class="blurme">One</span>
<span class="blurme">Two</span>
<span class="blurme">Three</span>
<span class="blurme">Four</span>
<span class="blurme">Five</span>
<span class="blurme">Six</span>
<br>
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">

css() doesn't get fired with first click

I'm trying to toggle the css of two buttons in a list. If one is clicked, the other one should have no border, and vice versa. Here's my code:
function navigate_menu(event, ec){
$(event).css("border-top", "3px solid rgba(102,205,0, 0.8)");
var search_id=$(event).attr("name");
var chartid = "pie_chart_"+$(event).attr("name");
var editid = "edit_"+$(event).attr("name");
if(ec=="c"){
$(".li-edit").css("border-top", "0px solid rgba(102,205,0, 0.8)");
$("#"+chartid).appendTo($("#chart_"+search_id+"_container"));
$("#"+editid).css("display","none");
$("#"+chartid).css("display","block");
}else{
$(".li-chart").css("border-top", "0px solid rgba(102,205,0, 0.8)");
$("#"+editid).appendTo($("#chart_"+search_id+"_container"));
$("#"+chartid).css("display","none");
$("#"+editid).css("display","block");
}
}
HTML:
+"<ul id=\"navigation_list\">"
+"<li onclick=\"navigate_menu(this,'c')\" class=\"li-chart\" name=\""+search_id+"\">Chart & Legend</li>"
+"<li onclick=\"navigate_menu(this,'e')\" class=\"li-edit\" name=\""+search_id+"\">Edit Chart\\Change Data</li>"
+"</ul>"
So, when I first click, nothing happens, and then after the second it works. Then when I click on the other button, same (first nothing, second works). I thought that maybe on the first click it thinks I click on the parent (ul), but I don't know how would I fix it. And sorry for the pluses, its because this "menu" gets added to multiple elements from a JS function.
I have also tried addClass() and removeClass(), still same outcome.
Thank you!
Give each a li a shared class, e.g. li-item:
<ul id="navigation_list">
<li onclick="navigate_menu(this,'c')" class="li-chart li-item" name="+search_id+">Chart & Legend</li>
<li onclick="navigate_menu(this,'e')" class="li-edit li-item" name="+search_id">Edit Chart Change Data</li>
</ul>
Then use a JQuery .on("click" function to detect the click and apply the border to the clicked and remove from all others:
$(document).ready(function() {
$(document).on("click", ".li-item", function() {
$(this).addClass("border");
$(".li-item").not($(this)).removeClass("border");
})
})
Make a CSS class with the style to apply:
.border {
border: 2px solid blue;
}
Fiddle: https://jsfiddle.net/w9bwq57m/
Create bordered class in your css. Then call this fn somewhere in your click handler by passing element and second argument (no idea how to name it) I just wrote context. Make sure that you have deleted obsolete staff from the code above , which is responsible for border change .
function toggleBorder(element, context){
if(context === 'c'){
if($(".li-chart").hasClass('bordered')){
$(".li-chart").removeClass('bordered');
}
$(".li-edit").addClass('bordered');
}else{
if($(".li-edit").hasClass('bordered')){
$(".li-edit").removeClass('bordered');
}
$(".li-chart").addClass('bordered');
}
}
I would suggest using jquery click instead of onlick on li elements. Also you'd need to add data-key="c" and data-key="e" to the li elements so those values can be passed to the function:
$("#navigation_list li").click(function () {
navigate_menu(this, $(this).data('key'));
});

Javascript onclick menu change background colors

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/

Using JS, how do I swap out a specifc instance of text instead of all instances?

Sorry if this is a really noobish question but I have just made a form with sections that are toggle-able. Each section has a '.header' which on click will perform a slideToggle on the section div.
I would like to add a triangle either pointing down or sideways to let people know it is toggle-able. (i.e ▶ or ▼).
I have the triangle in a span with the class '.arrowTog'
I was able to get partial success with
$('.header').on('click', function() {
if ($('.arrowTog').text().contains('▼')){
$('.arrowTog').text('▶');
}else{
$('.arrowTog').text('▼');
}
});
When I clicked on one all of the triangles swapped so I tried this (which causes none of them to rotate at all):
$('.header').on('click', function() {
if ($(this).prev('.arrowTog').text().contains('▼')){
$(this).prev('.arrowTog').text('▶');
}else{
$(this).prev('.arrowTog').text('▼');
}
});
This is a sample of the HTML
<div class="header" style="cursor: pointer;">
<span class="arrowTog">▶ </span>
<b>Merchant</b>
</div>
<div class="searchContent" style="display:none;">
Any ideas what I am doing wrong?
Thanks!
In your first version, the problem is you're finding every .arrowTog in the page. You can use the fact that within the click handler, this is bound to the element that was clicked, and then just search within that using find:
$('.header').on('click', function() {
var arrow = $(this).find('.arrowTog');
if (arrow.text().contains('▼')){
arrow.text('▶');
} else {
arrow.text('▼');
}
});
You're using a class. You probably have a number of elements with the same class in it, so jQuery is matching all of them and doing this transformation to all of them.
Use a context (All .arrowTog RIGHT INSIDE THIS NODE):
$('.header').on('click', function(evt) {
if ($('.arrowTog', evt.target).text().contains('▼')){
$('.arrowTog', evt.target).text('▶');
}else{
$('.arrowTog', evt.target).text('▼');
}
});
Why not use CSS?
.arrowTog:before {
content: '▶';
}
.arrowTog.open:before {
content: '▼';
}
And then
$('.header').on('click', function() {
$(this).toggleClass('open');
});

Hiding content depending on variable value

I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});

Categories