Trying to make an if statement in JS that when one of the top 3 buttons changes, it checks which of the bottom 2 has the "active" class. and visa versa
So when I click 30g it will check if option a or option b is active, and then change the price accordingly.
Any help would be greatly appreciated as I'm kind of a noob.
$(function(){
$('ul.nav li').on('click', function(){
$(this).parent().find('li.activeBtn').removeClass('activeBtn');
$(this).addClass('activeBtn');
});
});
function myFunction(){
const element = document.getElementById("30");
const element2 = document.getElementById("no");
const pricetag = document.getElementById("price");
if(((element.classList.contains("activeBtn")) == true) && ((element2.classList.contains("activeBtn")) == true)){
pricetag.innerHTML = "€1,00";
}
}
ul.nav a {
border: 2px solid #E1E8EE;
border-radius: 6px;
padding: 13px 20px;
font-size: 14px;
color: #5E6977;
background-color: #fff;
cursor: pointer;
transition: all .5s;
display: inline-block;
vertical-align: middle;
}
.activeBtn {
color: grey;
font-weight: 1000;
border: 2px solid grey;
border-radius: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="nav">
<li id="30" onclick="myFunction()" class="activeBtn"><a>30g</a></li>
<li id="70" onclick="myFunction()"><a>70g</a></li>
<li id="90" onclick="myFunction()"><a>90g</a></li>
</ul>
<ul class="nav">
<li id="no" class="activeBtn"><a>Zonder kreeftensoep</a></li>
<li id="yes"><a>Met kreeftensoep</a></li>
</ul>
<br>
<div class="product-price">
<span id="price">148$</span>
</div>
Are you trying to update the total price depending on which element is already selected ?
If that's the case, you can use a for loop event binding ->
// You should add a '.nav__el' class to your <li> elements in html
const navEls = document.querySelectorAll('.nav__el')
// Bind an event listener to all your buttons
navEls.forEach(el => {
el.addEventListener('click', () => {
const domPrice = document.querySelector('#price')
// Get the price related to your button
const price = el.getAttribute('data-price')
// Get the current total
const currentPrice = parseInt(domPrice.innerText)
if(el.classList.contains('activeBtn')) {
el.classList.remove('activeBtn')
domPrice.innerText = `${currentPrice - price}$`
}
else {
el.classList.add('activeBtn')
domPrice.innerText = `${currentPrice + price}$`
}
})
})
I have a todo project with localStorage and SortableJS. I am having problem where when I sort my todo list, it won't update the localStorage. Can somebody help me figure out a way to save the sorted list? The code is below but would be nice to visit the codepen link under the snippet.
const clear = document.querySelector(".clear");
const dateElement = document.getElementById("date");
const list = document.getElementById("list");
const input = document.getElementById("input");
// Class names
const CHECK = "fa-check-circle";
const UNCHECK = "fa-circle-thin";
const LINE_THROUGH = "lineThrough";
// Variables
let LIST, id;
// Get item from localStorage
let data = localStorage.getItem("TODO");
// Check if data is not empty
if (data) {
LIST = JSON.parse(data);
id = LIST.length;
loadList(LIST);
} else {
LIST = [];
id = 0;
}
// Load items to the user's interface
function loadList(array) {
array.forEach(function(item) {
addToDo(item.name, item.id, item.done, item.trash);
});
}
// Clear the localStorage
clear.addEventListener("click", function() {
localStorage.clear();
location.reload();
})
// Show today's date
const options = {
weekday: "long",
month: "short",
day: "numeric"
};
const today = new Date();
dateElement.innerHTML = today.toLocaleDateString("en-US", options);
// Add to do function
function addToDo(toDo, id, done, trash) {
if (trash) {
return;
}
const DONE = done ? CHECK : UNCHECK;
const LINE = done ? LINE_THROUGH : "";
const item = `<li class="item">
<i class="fa ${DONE}" job="complete" id="${id}"></i>
<p class="text ${LINE}">${toDo}</p>
<i class="fa fa-trash-o de" job="delete" id="${id}"></i>
</li>
`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
}
// Add an item to the list when the user cick the enter key
document.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
const toDo = input.value;
// If the input isn't empty
if (toDo) {
addToDo(toDo);
LIST.push({
name: toDo,
id: id,
done: false,
trash: false
});
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
id++;
}
input.value = ""
}
});
// complete to do
function completeToDo(element) {
element.classList.toggle(CHECK);
element.classList.toggle(UNCHECK);
element.parentNode.querySelector(".text").classList.toggle(LINE_THROUGH);
LIST[element.id].done = LIST[element.id].done ? false : true;
}
// Remove to do
function removeToDo(element) {
element.parentNode.parentNode.removeChild(element.parentNode);
LIST[element.id].trash = true;
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
}
// Target the items created dynamically
list.addEventListener("click", function(event) {
const element = event.target;
const elementJob = element.attributes.job.value;
if (elementJob == "complete") {
completeToDo(element);
} else if (elementJob == "delete") {
removeToDo(element);
}
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
});
// For sorting the list
Sortable.create(list, {
animation: 100,
group: 'list-1',
draggable: '#list li',
handle: '#list li',
sort: true,
filter: '.sortable-disabled',
chosenClass: 'active'
});
/* ------------ youtube.com/CodeExplained ------------ */
body {
padding: 0;
margin: 0;
background-color: rgba(0, 0, 0, 0.1);
font-family: 'Titillium Web', sans-serif;
}
/* ------------ container ------------ */
.container {
padding: 10px;
width: 380px;
margin: 0 auto;
}
/* ------------ header ------------ */
.header {
width: 380px;
height: 200px;
background-image: url('');
background-size: 100% 200%;
background-repeat: no-repeat;
border-radius: 15px 15px 0 0;
position: relative;
}
.clear {
width: 30px;
height: 30px;
position: absolute;
right: 20px;
top: 20px;
}
.clear i {
font-size: 30px;
color: #FFF;
}
.clear i:hover {
cursor: pointer;
text-shadow: 1px 3px 5px #000;
transform: rotate(45deg);
}
#date {
position: absolute;
bottom: 10px;
left: 10px;
color: #FFF;
font-size: 25px;
font-family: 'Titillium Web', sans-serif;
}
/* ------------ content ------------ */
.content {
width: 380px;
height: 350px;
max-height: 350px;
background-color: #FFF;
overflow: auto;
}
.content::-webkit-scrollbar {
display: none;
}
.content ul {
padding: 0;
margin: 0;
}
.item {
width: 380px;
height: 45px;
min-height: 45px;
position: relative;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
list-style: none;
padding: 0;
margin: 0;
}
.item i.co {
position: absolute;
font-size: 25px;
padding-left: 5px;
left: 15px;
top: 10px;
}
.item i.co:hover {
cursor: pointer;
}
.fa-check-circle {
color: #6eb200;
}
.item p.text {
position: absolute;
padding: 0;
margin: 0;
font-size: 20px;
left: 50px;
top: 5px;
background-color: #FFF;
max-width: 285px;
}
.lineThrough {
text-decoration: line-through;
color: #ccc;
}
.item i.de {
position: absolute;
font-size: 25px;
right: 15px;
top: 10px;
}
.item i.de:hover {
color: #af0000;
cursor: pointer;
}
/* ------------ add item ------------ */
.add-to-do {
position: relative;
width: 360px;
height: 40px;
background-color: #FFF;
padding: 10px;
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.add-to-do i {
position: absolute;
font-size: 40px;
color: #4162f6;
}
.add-to-do input {
position: absolute;
left: 50px;
height: 35px;
width: 310px;
background-color: transparent;
border: none;
font-size: 20px;
padding-left: 10px;
}
.add-to-do input::-webkit-input-placeholder {
/* Chrome/Opera/Safari */
color: #4162f6;
font-family: 'Titillium Web', sans-serif;
font-size: 20px;
}
.add-to-do input::-moz-placeholder {
/* Firefox 19+ */
color: #4162f6;
font-family: 'Titillium Web', sans-serif;
font-size: 20px;
}
.add-to-do input:-ms-input-placeholder {
/* IE 10+ */
color: #4162f6;
font-family: 'Titillium Web', sans-serif;
font-size: 20px;
}
.add-to-do input:-moz-placeholder {
/* Firefox 18- */
color: #4162f6;
font-family: 'Titillium Web', sans-serif;
font-size: 20px;
}
<script src="https://kit.fontawesome.com/ed2e310181.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/RubaXa/Sortable/Sortable.min.js"></script>
<div class="container">
<div class="header">
<div class="clear">
<i class="fa fa-refresh"></i>
</div>
<div id="date"></div>
</div>
<div class="content">
<ul id="list">
<!-- <li class="item">
<i class="fa fa-circle-thin co" job="complete" id="0"></i>
<p class="text"></p>
<i class="fa fa-trash-o" job="delete" id="1"></i>
</li> -->
</ul>
</div>
<div class="add-to-do">
<i class="fa fa-plus-circle"></i>
<input type="text" id="input" placeholder="Add a to-do">
</div>
</div>
Please visit my codepen for a working project.
Try to add 2 or more todos then sort, on refresh was hoping to keep the sorted list.
https://codepen.io/Foxseiz/pen/ZEGadWZ
Sortable.create(list, {
group: "TODO2",
options: {
animation: 100,
draggable: "#list li",
handle: "#list li",
sort: true,
filter: ".sortable-disabled",
chosenClass: "active"
},
store: {
/**
* Get the order of elements. Called once during initialization.
* #param {Sortable} sortable
* #returns {Array}
*/
get: function(sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split("|") : [];
},
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* #param {Sortable} sortable
*/
set: function(sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join("|"));
}
}
});
That would work in your case
For your Sortable.create option you can do the following:
// For sorting the list
Sortable.create(list, {
animation: 100,
group: 'list-1',
draggable: '#list li',
handle: '#list li',
sort: true,
filter: '.sortable-disabled',
chosenClass: 'active',
onSort: function(e) {
var items = e.to.children;
var result = [];
for (var i = 0; i < items.length; i++) {
result.push(items[i].id);
}
var lsBefore = JSON.parse(localStorage.getItem("TODO"));
var lsAfter = [];
for (var i = 0; i < result.length; i++) {
var found = false;
for (var j = 0; j < lsBefore.length && !found; j++) {
if (lsBefore[j].id == result[i]) {
lsAfter.push(lsBefore[j]);
lsBefore.splice(j, 1);
found = true;
}
}
}
localStorage.setItem("TODO", JSON.stringify(lsAfter));
console.log(result);
console.log(lsBefore);
console.log(lsAfter);
}
The lsAfter is your re-sorted set of objects that you can store/update in local storage.
My solution also requires that your const item looks like this (I added the id attribute to the <li> element:
const item = `<li class="item" id="${id}">
<i class="fa ${DONE}" job="complete" id="${id}"></i>
<p class="text ${LINE}">${toDo}</p>
<i class="fa fa-trash-o de" job="delete" id="${id}"></i>
</li>
`;
You need use onSort callback.
example code:
const clear = document.querySelector(".clear");
const dateElement = document.getElementById("date");
const list = document.getElementById("list");
const input = document.getElementById("input");
// Class names
const CHECK = "fa-check-circle";
const UNCHECK = "fa-circle-thin";
const LINE_THROUGH = "lineThrough";
// Variables
let LIST, id;
// Get item from localStorage
let data = localStorage.getItem("TODO");
// Check if data is not empty
if(data) {
LIST = JSON.parse(data);
id = LIST.length;
loadList(LIST);
}else{
LIST =[];
id = 0;
}
// Load items to the user's interface
function loadList(array) {
array.forEach(function(item){
addToDo(item.name, item.id, item.done, item.trash);
});
}
// Clear the localStorage
clear.addEventListener("click", function() {
localStorage.clear();
location.reload();
})
// Show today's date
const options = {weekday : "long", month : "short", day : "numeric"};
const today = new Date();
dateElement.innerHTML = today.toLocaleDateString("en-US", options);
// Add to do function
function addToDo(toDo, id, done, trash) {
if(trash) { return; }
const DONE = done ? CHECK : UNCHECK;
const LINE = done ? LINE_THROUGH : "";
const item = `<li class="item">
<i class="fa ${DONE}" job="complete" id="${id}"></i>
<p class="text ${LINE}">${toDo}</p>
<i class="fa fa-trash-o de" job="delete" id="${id}"></i>
</li>
`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
}
// Add an item to the list when the user cick the enter key
document.addEventListener("keyup", function(event) {
if(event.keyCode == 13) {
const toDo = input.value;
// If the input isn't empty
if(toDo) {
addToDo(toDo);
LIST.push({
name : toDo,
id : id,
done : false,
trash : false
});
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
id++;
}
input.value = ""
}
});
// complete to do
function completeToDo(element) {
element.classList.toggle(CHECK);
element.classList.toggle(UNCHECK);
element.parentNode.querySelector(".text").classList.toggle(LINE_THROUGH);
LIST[element.id].done = LIST[element.id].done ? false : true;
}
// Remove to do
function removeToDo(element) {
element.parentNode.parentNode.removeChild(element.parentNode);
LIST[element.id].trash = true;
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
}
// Target the items created dynamically
list.addEventListener("click", function(event) {
const element = event.target;
const elementJob = element.attributes.job.value;
if(elementJob == "complete") {
completeToDo(element);
}else if(elementJob == "delete"){
removeToDo(element);
}
// Add item to localStorage
localStorage.setItem("TODO", JSON.stringify(LIST));
});
function swapArrayElements(arr, indexA, indexB) {
var temp = arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = temp;
};
function orderList(oldIndex, newIndex) {
swapArrayElements(LIST, oldIndex, newIndex)
localStorage.setItem("TODO", JSON.stringify(LIST));
}
// For sorting the list
Sortable.create(list, {
animation: 100,
group: 'list-1',
draggable: '#list li',
handle: '#list li',
sort: true,
filter: '.sortable-disabled',
chosenClass: 'active',
onSort: function (/**Event*/evt) {
orderList(evt.oldIndex, evt.newIndex);
},
});
When you call
Sortable.create(list, {
animation: 100,
group: 'list-1',
draggable: '#list li',
handle: '#list li',
sort: true,
filter: '.sortable-disabled',
chosenClass: 'active'
});
There is actually a store option you can add. Like this:
Sortable.create(list, {
store: {
//Get the order of elements. Called once during initialization.
// #param {Sortable} sortable
// #returns {Array}
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
// Save the order of elements.
// #param {Sortable} sortable
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
},
...rest of your options
});
Also Sortable.create returns a "Sortable" object for your list so building on the code you have above you now have access to the Sortable object
var mySortable = Sortable.create(list, {...your options});
Now you can call mySortable.Save() after any event and your store's set function will get called. For example put mysortable.Save() in your document.addEventListener("keyup") function
Currently I have a number of clickable boxes that when I hover over them, they change colour. When I click and hold on a specific box, it changes colour.(by using :active in css.
Is there anyway I can make the colour of the border change permanently until a different box is clicked? E.G the same as the :active property except I don't have to keep the mouse held in?
My Code:
flight-viewer.html
<h3>Flights </h3>
<div>
<ul class= "grid grid-pad">
<a *ngFor="let flight of flights" class="col-1-4">
<li class ="module flight" (click)="selectFlight(flight)">
<h4>{{flight.number}}</h4>
</li>
</a>
</ul>
</div>
<div class="box" *ngIf="flightClicked">
<!--<flight-selected [flight]="selectedFlight"></flight-selected>-->
You have selected flight: {{selectedFlight.number}}<br>
From: {{selectedFlight.origin}}<br>
Leaving at: {{selectedFlight.departure || date }}<br>
Going to: {{selectedFlight.destination}}<br>
Arriving at: {{selectedFlight.arrival || date}}
</div>
flight-viewer.css:
h3 {
text-align: center;
margin-bottom: 0;
}
h4 {
position: relative;
}
ul {
width: 1600px;
overflow-x: scroll;
background: #ccc;
white-space: nowrap;
vertical-align: middle;
}
div
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
li {
display: inline-block;
/* if you need ie7 support */
*display: inline;
zoom: 1
}
.module {
padding: 20px;
text-align: center;
color: #eee;
max-height: 120px;
min-width: 120px;
background-color: #607D8B;
border-radius: 2px;
}
.module:hover {
background-color: #EEE;
cursor: pointer;
color: #607d8b;
}
.module:active {
border: 5px solid #73AD21;
}
.box {
text-align: center;
margin-bottom: 0;
margin: auto;
width: 600px;
position:absolute;
top: 180px;
right: 0;
height: 100px;
border: 5px solid #73AD21;
text-align: center;
display: inline-block;
}
flight-viewer-component.ts:
import { Component } from '#angular/core';
import { FlightService } from './flight.service';
import { Flight } from './flight.model'
#Component({
selector: 'flight-viewer',
templateUrl: 'app/flight-viewer.html',
styleUrls: ['app/flight-viewer.css']
})
export class FlightViewerComponent {
name = 'FlightViewerComponent';
errorMessage = "";
stateValid = true;
flights: Flight[];
selectedFlight: Flight;
flightToUpdate: Flight;
flightClicked = false;
constructor(private service: FlightService) {
this.selectedFlight = null;
this.flightToUpdate = null;
this.fetchFlights();
}
flightSelected(selected: Flight) {
console.log("Setting selected flight to: ", selected.number);
this.selectedFlight = selected;
}
flightUpdating(selected: Flight) {
console.log("Setting updateable flight to: ", selected.number);
this.flightToUpdate = selected;
}
updateFlight(flight: Flight) {
let errorMsg = `Could not update flight ${flight.number}`;
this.service
.updateFlight(flight)
.subscribe(() => this.fetchFlights(),
() => this.raiseError(errorMsg));
}
selectFlight(selected: Flight) {
console.log("Just click on this flight ", selected.number, " for display");
this.flightClicked = true;
this.selectedFlight = selected;
}
private fetchFlights() {
this.selectedFlight = null;
this.flightToUpdate = null;
this.service
.fetchFlights()
.subscribe(flights => this.flights = flights,
() => this.raiseError("No flights found!"));
}
private raiseError(text: string): void {
this.stateValid = false;
this.errorMessage = text;
}
}
Thanks!
I'm quite sure that this has already been answered.
Make your DIVs focusable, by adding tabIndex:
<div tabindex="1">
Section 1
</div>
<div tabindex="2">
Section 2
</div>
<div tabindex="3">
Section 3
</div>
Then you can simple use :focus pseudo-class
div:focus {
background-color:red;
}
Demo: http://jsfiddle.net/mwbbcyja/
You can use the [ngClass] directive provided by angular to solve your problem.
<a *ngFor="let flight of flights" class="col-1-4">
<li [ngClass]="{'permanent-border': flight.id === selectedFlight?.id}" class ="module flight" (click)="selectFlight(flight)">
<h4>{{flight.number}}</h4>
</li>
</a>
This will add the css class permantent-border to the <li> element, if the id of the flight matches the id with the selectedFlight (Assuming you have an id proberty specified, or just use another proberty which is unique for the flight)
I'm looking to learn how to do this left menu :
http://js.devexpress.com/New/15_2/#HTML_5_JS_Core
When you scroll down the page, the "active" menu item change.
p.s.
Is there a name for this type of menu?
regards,
yaniv
Scroll Navigation
That is how we call these type of navigation bars. Basically you have to listen to the scroll event and calculate which element is in the viewport at the moment than you add a class to your navigation that marks the current menu element.
There is a nice demo built in jQuery but because jQuery is a thing of the past, I built one in Vanilla JS. See comments for explanations.
There are different ways to define which is the current element. In my Example it is the last one whose top line just passed the top line of the browser.
Working demo
window.onscroll = onScroll;
function onScroll() {
var removeActiveClass = function (elements) {
for (var i = 0; i < elements.length; ++i) {
elements[i].classList.remove('active');
}
}
var anchors = document.querySelectorAll('#menu-center a');
var previousRefElement = null;
for (var i = 0; i < anchors.length; ++i) {
// Get the current element by the id from the anchor's href.
var currentRefElement = document.getElementById(anchors[i].getAttribute('href').substring(1));
var currentRefElementTop = currentRefElement.getBoundingClientRect().top;
// Searching for the element whose top haven't left the top of the browser.
if (currentRefElementTop <= 0) {
//The browser's top line haven't reached the current element, so the previous element is the one we currently look at.
previousRefElement = anchors[i];
// Edge case for last element.
if (i == anchors.length - 1) {
removeActiveClass(anchors);
anchors[i].classList.add("active");
}
} else {
removeActiveClass(anchors);
previousRefElement.classList.add("active");
break;
}
}
}
body, html {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
.menu {
width: 100%;
height: 75px;
position: fixed;
background-color:rgba(4, 180, 49, 0.6);
}
#menu-center {
width: 980px;
height: 75px;
margin: 0 auto;
}
#menu-center ul {
margin: 15px 0 0 0;
}
#menu-center ul li {
list-style: none;
margin: 0 30px 0 0;
display: inline;
}
.active {
font-size: 14px;
color: #fff;
text-decoration: none;
line-height: 50px;
}
a {
font-size: 14px;
color: black;
text-decoration: none;
line-height: 50px;
}
.content {
height: 100%;
width: 100%;
}
#portfolio {background-color: grey;}
#about {background-color: blue;}
#contact {background-color: red;}
<div class="menu">
<div id="menu-center">
<ul>
<li><a class="active" href="#home">Home</a></li>
<li>Portfolio</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="home" class="content"></div>
<div id="portfolio" class="content"></div>
<div id="about" class="content"></div>
<div id="contact" class="content"></div>
This is not exactly menu type, it is the way how you can position objects by html.
You can use position:Abosule property to achieve this effect:
http://www.w3schools.com/css/tryit.asp?filename=trycss_position_fixed
By this given divs are "flying" above the res of the page. In your case it could be a menu.
EDIT:
To sync this you need to detect when given anchor is currently seen.
It can be done by jQuery, this is sample draft of code, should explain clue of solution:
// list of header on page
var positions = [
$("#anchor1").offset().top,
$("#anchor2").offset().top,
$("#anchor3").offset().top,
];
var menu_objects= [
"#menu1",
"#menu2",
"#menu3"
];
var $w = $(window).scroll(function(){
// clear old
for(var v in menu_objects)
$(v).css({"color","white"});
for(var i=positions.length-1;i>=0;i--)
{
if(positions[i]>=$w.scrollTop())
{
$(menu_objects[i]).css({"color","red"});
break;
}
}
});
I'm trying to have a bgcolor change for an element on mouseover, mouseout, and onclick. The problem is Javascript overwrites my onclick with mouseout, so I can't have both. So is there any way to have mouseover reset after mouseout?
function init() {
document.getElementById('default').onmouseover = function() {
tabHoverOn('default', 'grey')
};
document.getElementById('default').onmouseout = function() {
tabHoverOff('default', 'yellow')
};
document.getElementById('section2').onmouseover = function() {
tabHoverOn('section2', 'grey')
};
document.getElementById('section2').onmouseout = function() {
tabHoverOff('section2', 'yellow')
};
document.getElementById('section3').onmouseover = function() {
tabHoverOn('section3', 'grey')
};
document.getElementById('section3').onmouseout = function() {
tabHoverOff('section3', 'yellow')
};
}
function tabHoverOn(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
function tabHoverOff(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
var current = document.getElementById('default');
function tab1Highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab1highlight";
current = id;
}
function tab2highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab2highlight";
current = id;
}
function tab3highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab3highlight";
current = id;
}
window.onload = init();
body {
width: 900px;
margin: 10px auto;
}
nav {
display: block;
width: 80%;
margin: 0 auto;
}
nav > ul {
list-style: none;
}
nav > ul > li {
display: inline-block;
margin: 0 3px;
width: 150px;
}
nav > ul > li > a {
width: 100%;
background-color: #ffff66;
border: 1px solid #9b9b9b;
border-radius: 12px 8px 0 0;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
font-family: arial, sans-serif;
}
main {
display: block;
width: 80%;
margin: 0 auto;
border: 1px solid #9b9b9b;
padding: 10px;
}
main > h1 {
font-size: 1.5em;
}
.tab1highlight {
background-color: #339966;
color: white;
}
.tab2highlight {
background-color: #ff6666;
color: white;
}
.tab3highlight {
background-color: #6600ff;
color: white;
}
main img {
border: 5px solid #eeefff;
width: 80%;
margin-top: 20px;
}
<body>
<nav>
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</nav>
<main>
<h1>Exercise: Navigation Tab #5</h1>
<ul>
<li>
Combine the navigation tab exercises #1, #3, and #4 in one file, including <br>
<ul>
<li>temporarily change the background color of a tab when the cursor is hovering on it.</li>
<li>set the foreground and background color of the tab being clicked.</li>
<li>change the background color of the main element based on the selected tab.</li>
</ul>
<p>
To test, click on a tab and then move your mouse around. For example, the third tab is clicked, the tab background color is switched to blue. Then hover the mouse over the third tab, the background color of the tab should be switch to light green and then back to blue after the mouse moves out.
</p>
<img src="menu_tab5.jpg">
</li>
</ul>
</main>
It's generally a good idea to keep CSS out of JavaScript completely if you can help it. A better strategy for solving the hover problem is to use the CSS pseudo selector :hover rather than coding the color changes in JavaScript. If you give all your tabs the same class, you only have to write the CSS once:
.tab {
background-color: yellow;
}
.tab:hover {
background-color: grey;
}
Once you've done that, you can also relegate the click styling to CSS by creating an event handler that adds and removes a special class each time a tab is clicked.
In the CSS file:
.tab.clicked {
background-color: blue;
}
And then in JavaScript, something like:
var tabs = document.getElementsByClassName('tab');
for (i = 0; i < tabs.length; i ++) {
tabs[i].onclick = function (ev) {
for (i = 0; i < tabs.length; i ++) {
tabs[i].classList.remove('clicked');
}
ev.currentTarget.classList.add('clicked');
};
}
I've created a JSFiddle to illustrate.
Try updating a Boolean variable.
var Ele = document.getElementById('default');
var clicked = false;
Ele.onclick = function(){
clicked = true;
// add additional functionality here
}
Ele.onmouseover = function(){
clicked = false;
// add additional functionality here
}
Ele.onmouseout = function(){
if(!clicked){
// add additional functionality here
}
}