first website, need assistance with certain click function - javascript

I have two tabs on this option. I have already created a mouseover and mouseleave for these two tabs. When you highlight one or the other, they share a background color.
However, now I am creating a click function. When you click on one of these tabs, I would like for it to maintain that background color, and even if the user highlighted the second time, it would not change color this time. Reason I want to do this is to show which tab is active, because each will have its own seperate content which will appear will clicked within the same div.
HTML code:
<div class="meal-details">
<h4>Lobster & Summer Vegetables with Spicy Herbed Butter</h4>
<h5 class="optiontabs meal-description">DESCRIPTION</h5>
<h5 class="optiontabs nutrition-description">NUTRITIONAL INFO</h5>
<div class="nutrition-breakdown">
<p>This is the nutrition info bro</p>
</div>
<div class="meal-breakdown">
<p>The meal breakdown and descrition.</p>
</div>
</div>
JQuery:
$(document).ready(function() {
$(".optiontabs").mouseover(function() {
$(this).css("background-color", "#3e597c");
});
$(".optiontabs").mouseleave(function() {
$(this).css("background-color", "#141C25");
});
$(".nutrition-description").click(function() {
$(this).css("background-color", "#3e597c");
$(this).nextAll(".nutrition-breakdown").css("display", "initial");
$(this).nextAll(".meal-breakdown").css("display", "none");
});
});
My question is, what is the best method to use in order to achieve what I have mentioned above. I have asked Jquery to change the background-color of the active tab but its not doing it. What am I doing wrong?
Thanks for the help in advance!

You have to unbind the mouseover and mouseleave once you click on an element once. You can do that using the $('element').off('event') syntax. Please look at the following code:
$(document).ready(function() {
var countClick = 0;
if(countClick==0) {
$(".optiontabs").mouseover(function() {
$(this).css("background-color", "#3e597c");
});
$(".optiontabs").mouseleave(function() {
$(this).css("background-color", "#141C25");
});
}
$(".nutrition-description").click(function() {
$(".optiontabs").off("mouseleave");
$(".optiontabs").off("mouseover");
countClick++;
$(this).css("background-color", "#3e597c");
$(this).nextAll(".nutrition-breakdown").css("display", "initial");
$(this).nextAll(".meal-breakdown").css("display", "none");
});
});

Related

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

Change background colour of parent div upon child hover in css?

I'm working on a web design assignment and I'm fairly uncomfortable with most css styles thus far, this task involves 3 coloured boxes in a div. I have to turn the white background of this div to the same colour of the box when the box is hovered.
HTML:
<div id="t1_color_one" class="t1_colors" style="background: goldenrod;"></div>
<div id="t1_color_two" class="t1_colors" style="background: lightgreen;"></div>
<div id="t1_color_three" class="t1_colors" style="background: palevioletred;"></div>
Not trying to be "that guy" who asks stupid questions.. but I literally have no idea how to approach this. Thanks for any tips, greatly appreciated
I think Jeremy means that the outside div id="task1" has to assume the color of the hovered inside div, so the solution is to use javascript:
$('.t1_colors').hover(function(){
$('#task1').css('background-color', $(this).css('background-color'));
},
function(){
$('#task1').css('background-color', white);
}
);
here is working example, is this what you wanted >> http://jsfiddle.net/mbTBu/
$(document).ready(function(){
$(".t1_colors").hover(function(){
var $c=$(this).css("background-color");
$("#task1").css('background-color', $c);
});
});
you can also use, mouseover & mouseout function to revert back the color.
http://jsfiddle.net/mbTBu/2/
Here is answer in pure javascript
window.addEventListener('load', function(event)
{
var divs = document.getElementsByClassName('t1_colors');
var count_of_divs = divs.length;
for(var i = 0; i<count_of_divs; i++)
{
divs[i].addEventListener('mouseover', function(e)
{
document.getElementById('task1').setAttribute('style', e.target.getAttribute('style'));
}, false);
divs[i].addEventListener('mouseout', function(e)
{
document.getElementById('task1').removeAttribute('style');
}, false)
}
}, false);
And you can check it in jsFiddle link.

jQuery Show & Hide Toggle

I have some divs that need to be hidden (class named .hideable), and some divs that need to be shown (class named .toggleable. I have it working so far, which is great, but I`m having difficulties with the following; The hidden divs (.hideable) need to come back after the toggleable divs are hidden again.
here is what I have:
jQuery(document).ready(function($) {
var topContainer = $(".toggleable");
var topButton = $(".orsp a");
topButton.click(function() {
topContainer.slideToggle('slow');
$(".hideable").hide();
});
});
all help is welcome!
thanks,
J.
Use jQuery.toggle()
$(".hideable").toggle();
instead of jQuery.hide()
I think you wnat try like this
HTML
<div style='display:none' class='hideable' >Hidden Div</div>
<div class='toggleable'>Toggleable div</div>
<input class='topButton' type='button' value='toggle'>
JS
$('.topButton').click(function() {
$('.toggleable').slideToggle('slow', function() { $(".hideable").slideToggle(); });
});
Fiddle Here
If you don't want to use toggle to hide the .hideable div you can hide it using CSS and whenever you toggle .toggleable div you can check with Jquery whether it is hidden and if it is you can change it back to be shown. However Jakub's answer is the simplest solution.
jQuery(document).ready(function($) {
var topContainer = $(".toggleable");
var topButton = $(".orsp a");
topButton.toggle(function() {
topContainer.slideToggle('slow');
$(".hideable").hide();
},function () {
topContainer.slideToggle('slow');
$(".toggleable").hide();
});
});
Simplest choose toggle or toggle class
Fiddle
<http://jsfiddle.net/gcsHg/>?

Jquery Expand Collapse all divs on Click

I know this has been asked a thousand times but I'm still having trouble figuring it out. I have a simple according following this tutorial and I'm trying to add an "expand/collapse all" link. I have found a way to expand all but can't figure out how to collapse them. The problem with a slideToggle() solution is if I open one then click the link it will close/open all of them but the one that was previoiusly active.
I set up a jsFiddle here.
Here is an overview of the code:
HTML:
<h2 class="acc_trigger">Div 1</h2>
<div class="acc_container">
<div class="block"> Yay content!</div>
</div>
<h2 class="acc_trigger">Div 2</h2>
<div class="acc_container">
<div class="block">More Content, Score!</div>
</div>
<h2 class="acc_trigger">Div 3</h2>
<div class="acc_container">
<div class="block">Even More Content</div>
</div>
Expand/Collapse All
JS:
jQuery(document).ready(function($) {
//Set default open/close settings
$('.acc_container').hide(); //Hide/close all containers
//On Click
$('.acc_trigger').click(function(){
$('.acc_trigger').removeClass('active').next().slideUp();
//Remove all "active" state and slide up the immediate next container
$(this).toggleClass('active').next().slideDown();
return false; //Prevent the browser jump to the link anchor
});
$('.acc_expand-all').click(function(){
//expand all on click
$('.acc_trigger').addClass('active').next().slideDown();
return false;
});
});
You have to check in your expand/collapse handler to see how many are open, etc., something like this (updated fiddle):
$('.acc_expand-all').click(function(){
var all = $('.acc_trigger'),
active = all.filter('.active');
if (all.length && all.length === active.length) {
// All open; close them
all.removeClass('active').next().slideUp();
}
else {
// At least some are closed, open all
all.not('.active').addClass('active').next().slideDown();
}
return false;
});
Regarding your question in the comments, you can check to see whether you should be in "exclusive" mode or not by checking how many are open and whether the clicked one is open, e.g. (updated fiddle):
$('.acc_trigger').click(function(){
var $this = $(this),
thisActive = $this.hasClass('active'),
active;
// If this one is active, we always just close it.
if (thisActive) {
$this.removeClass('active').next().slideUp();
}
else {
// Is there just one active?
active = $('.acc_trigger.active');
if (active.length === 1) {
// Yes, close it
active.removeClass('active').next().slideUp();
}
// Open this one
$this.addClass('active').next().slideDown();
}
});

Categories