save colour selector with local storage - javascript

so im trying to save colour selector to local storage so it will save the users selection after refreshing the page
this is a snippet of my code so far, if i remove the localstorage code from the script it will change colours but wont save the selection.
document.addEventListener('click', (e) => {
const colorOption = e.target.closest('.color-option');
if (!colorOption) return;
// unselect currently selected color options
document.querySelectorAll('.color-option').forEach(colorOption => colorOption.classList.remove('is-selected'));
colorOption.classList.add('is-selected');
const color = colorOption.dataset.color;
let root = document.documentElement;
root.style.setProperty('--primary-color', color);
localStorage.setItem(".color-option", "--primary-color");
localStorage.getItem("--primary-color");
});
body {
background-color: var(--primary-color);
}
.color-option {
height:35px;
width: 35px;
list-style: none;
border-radius: 4px;
margin: 7px;
transition: .2s;
cursor: pointer;
&:hover {
box-shadow: 0 0 0 5px rgba(0,0,0,.2);
}
&.is-selected {
transform: scale(1.1);
box-shadow: 0 0 0 5px rgba(0,0,0,.2);
}
}
.color-option:nth-child(1) { background: #3485fd }
.color-option:nth-child(2) { background: #002C5F }
.color-option:nth-child(3) { background: #00AFD8 }
.color-option:nth-child(4) { background: #5B1F69 }
.color-option:nth-child(5) { background: #FF5F1F }
.color-option:nth-child(6) { background: #ff00e2 }
<body>
<ul class="color-grid">
<li class="color-option is-selected" data-color="#3485fd"></li>
<li class="color-option" data-color="#002C5F"></li>
<li class="color-option" data-color="#00AFD8"></li>
<li class="color-option" data-color="#5B1F69"></li>
<li class="color-option" data-color="#FF5F1F"></li>
<li class="color-option" data-color="#ff00e2"></li>
</ul>
</body>
can't quite figure out what im doing wrong hopefully someone can help

You're almost there. As the other answer points out, you are not actually storing the selected color value.
You can think of localStorage as a store for key-value pairs. The syntax to set an item would be something like:
localStorage.setItem(<key>,<value>)
Where both key and value are strings. In order to store the user's color choice you'd have to do something like:
localStorage.setItem("selectedColor","#adadad")
Another missing piece is perhaps the code to load the previously selected color on page load.
PS: If you are trying to run this code in a sandbox (like the stack overflow code editor) you may not be able to access localStorage due to Cross Origin policies. Using localStorage in cases like this will throw an error (which may be why it works if you remove the localStorage part)
See sample implementation below:
const LS_COLOR_KEY = 'selected-color';
function selectColor(color){
document.querySelectorAll('.color-option').forEach(function(node){node.classList.remove('is-selected')});
document.querySelector('.color-option[data-color="'+color+'"]').classList.add('is-selected')
document.documentElement.style.setProperty("--primary-color", color);
localStorage.setItem(LS_COLOR_KEY, color);
}
document.addEventListener('DOMContentLoaded', function(){
// Retrieve and select any previously stored color
const storedColor = localStorage.getItem(LS_COLOR_KEY) || '#577590';
selectColor(storedColor);
})
document.addEventListener('click', function(e){
const colorOption = e.target.closest('.color-option');
if (!colorOption) return;
selectColor(colorOption.dataset.color);
})
:root {
--primary-color: transparent;
}
.color-option > .swatch {
height: 20px;
width: 20px;
margin: 0 0.25rem;
display: inline-block;
}
.color-option {
display: flex;
align-items: center;
margin: 0.25rem 0;
padding: 0.5rem 0;
cursor: pointer;
}
.color-option.is-selected{
border: 1px solid blue;
}
.selected-color {
background: var(--primary-color);
height: 100px;
width: 100px;
}
<div class="options">
<ul id="color-list">
<li data-color="#577590" class="color-option"><div class="swatch" style="background:#577590"> </div>Queen Blue</li>
<li data-color="#F3CA40" class="color-option"><div class="swatch" style="background:#F3CA40"></div>Maize Crayola</li>
<li data-color="#F08A4B" class="color-option"><div class="swatch" style="background:#F08A4B"></div>Mango Tango</li>
</ul>
</div>
<div class="selected-color"></div>

please check below
localStorage.setItem('bgcolor', 'red');
localStorage.getItem('bgcolor');
now look at your code, you have used .color-option as keyName,
but used another keyName in getItem --primary-color which is wrong.
localStorage.setItem(".color-option", "--primary-color");
localStorage.getItem("--primary-color");
it should be
localStorage.setItem(".color-option", "--primary-color-value");
localStorage.getItem(".color-option");

I don't think I get what you want really! but if you want to store the selected color in local storage and bring it back on every load you can save the actual value of the color and on every load, you will set the root property of the (--primary-color) to the value you stored. Like this
In your js file
let root = document.documentElement;
document.addEventListener("click", (e) => {
const colorOption = e.target.closest(".color-option");
if (!colorOption) return;
// unselect currently selected color options
document
.querySelectorAll(".color-option")
.forEach((colorOption) => colorOption.classList.remove("is-selected"));
colorOption.classList.add("is-selected");
const color = colorOption.dataset.color;
root.style.setProperty("--primary-color", color);
localStorage.setItem("selected-color", color);
});
window.onload = () => {
root.style.setProperty(
"--primary-color",
localStorage.getItem("selected-color")
);
};
I hope that solves what you want. thanks

Related

How to add a notification text in an HTML link and remove when clicked?

I'm creating a website which has daily news updates with URL links. I need to add a NEW! text on top of the link and once the user has visited it, need to remove the text. I searched for it everywhere what this feature is called and also went through anchor tag attribute in CSS i.e. a:visited {}, but it's only CSS, how can I use for the above scenario?
Also if there's any other way to deal with newly added links and after certain time, the NEW! text is gone, please let me know, I'm unable to find any resources online. Thanks.
You need a place where you store the article IDs once a user has read the news. The localStorage is a good choice. But cookies would also work.
In your article list you need the article ID for each article. For example, the data- Attribute is perfect for this. When you call up a page, the system will then
the visited pages are fetched from the localStoare and
the news list is collected
then you iterate the news list and compare the article id in the allreadyRead array.
Here is an example. I have skipped the localStorage part and already have the AllreadList array.
const allreadyVisited = ["101","102"];
const newsList = document.querySelectorAll('p');
newsList.forEach((el) => {
const newsID = el.getAttribute('data-id');
if (allreadyVisited.includes(newsID)) {
const badge = document.createElement('span');
badge.innerHTML = ' *NEW*';
el.append(badge)
}
})
<div id="list">
<p class="news" data-id="101">News One</p>
<p class="news" data-id="102">News Two</p>
<p class="news" data-id="103">News Three</p>
</div>
const link = document.querySelector('a').addEventListener('click', e => {
e.preventDefault()
// Chnage link class and color//
if (e.target.classList.contains('clicklink')){
//Get the text and remove it
document.querySelector('p').remove();
}
e.target.classList.add('visited')
})
Reusing this css answer: Badges For Buttons using html and CSS
You can use localStorage
const visited = ["- Visit my new blog post #3 -"]; // remove and uncomment next two lines
// const saved = localStorage.getItem("visited");
// const visited = saved ? JSON.parse(saved) : []; // restore what was visited here.
document.querySelectorAll("a.button").forEach(a => {
if (visited.includes(a.textContent)) a.classList.remove("badge")
})
document.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("badge")) {
const text = tgt.textContent;
if (!visited.includes(text)) {
visited.push(text);
tgt.classList.remove("badge")
// localStorage.setItem("visited",JSON.stringify(visited)); // uncomment
}
}
})
a { text-decoration:none }
.button {
background: linear-gradient(to bottom, rgba(37,130,188,1) 0%,rgba(41,137,216,1) 32%,rgba(41,137,216,1) 42%,rgba(175,224,234,1) 100%);
width: 60px;
height: 60px;
border-radius: 10px;
border: none;
margin-top: 40px;
margin-left: 40px;
position: relative;
box-shadow: 0 2px 5px rgba(0,0,0,0.4);
}
.button.badge:before {
content: "!";
width: 18px;
height: 18px;
line-height: 18px;
text-align: center;
display: block;
border-radius: 50%;
background: rgb(67, 151, 232);
border: 1px solid #FFF;
box-shadow: 0 1px 3px rgba(0,0,0,0.4);
color: #FFF;
position: absolute;
top: -7px;
left: -7px;
}
.button.badge.top-right:before {
left: auto;
right: -7px;
}
.button.badge.bottom-right:before {
left: auto;
top: auto;
right: -7px;
bottom: -7px;
}
.button.badge.bottom-left:before {
top: auto;
bottom: -7px;
}
- Visit my new blog post #1 - <hr/>
- Visit my new blog post #2 - <hr/>
- Visit my new blog post #3 -<hr/>
- Visit my new blog post #4 -

Loop through localStorage and show specific value on click

I need to make a shopping cart for my library project the issue here is that on a click of a certain book I cannot add it in another localStorage.
This is my html <!--Knjige-->
<div class="container grid" id='knjige'></div>
This is my CSS:
.container{
margin: 50px; }
.grid{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-gap: 20px;
align-items: start; }
.grid-card{
border: 1px solid #ccc;
box-shadow: 2px 2px 6px 0px rgba(0,0,0,0.3);
background: orange;
z-index: 9; }
.text:hover{
color: #fff;
cursor: pointer; }
.text{
padding: 0 20px 20px;
color: black;
font-weight: bold; }
And this is my JavaScript, please note that I'm not allowed to use jQuery
let knjige = [
{"Naziv":"4_50 From Paddington_ A Miss Marple Mystery",
"ID":"XA7JORPL",
"Autor":"Agatha Christie",
"Godina":"2007",
"Cena":546,
"Raspolozivo_stanje":50,
},
{"Naziv":"Lord Edgware Dies (1986, Berkley)",
"ID":"BPL6QUG5",
"Autor":"Agatha Christie",
"Godina":"1986",
"Cena":1041.06,
"Raspolozivo_stanje":15,
},
{"Naziv":"Murder at the Vicarage (2000, Signet)",
"ID":"T2CGKTQQ",
"Autor":"Agatha Christie",
"Godina":"2000",
"Cena":546,
"Raspolozivo_stanje":44,
},
{"Naziv":"Sparkling Cyanide (1989)",
"ID":"1QIFZZ4P",
"Autor":"Agatha Christie",
"Godina":"1989",
"Cena":1114.91,
"Raspolozivo_stanje":45,
},
{"Naziv":"The Mystery of the Blue Train",
"ID":"4C4XW7H2",
"Autor":"Agatha Christie",
"Godina":"1928",
"Cena":1041.06,
"Raspolozivo_stanje":"",
}
];
if(!localStorage.getItem('knjige')){
window.localStorage.setItem('knjige', JSON.stringify(knjige));
}
let knjigeLocalStorage = JSON.parse(window.localStorage.getItem('knjige'));
window.onload = function(show){
for(knjiga of knjigeLocalStorage){
show += `
<div class='grid-card'>
<div class='text'>
<h4>Naziv: ${knjiga.Naziv}</h4>
<p>Autor: ${knjiga.Autor}</p>
<p>ID: ${knjiga.ID}</p>
<p>Godina: ${knjiga.Godina}</p>
<p>Cena: ${knjiga.Cena}</p>
<p>Raspolozivo Stanje: ${knjiga.Raspolozivo_stanje}</p>
<button class='btn' id='dugme' onclick=''><i class="fas fa-shopping-cart"></i></button>
</div>
</div>
`;
};
document.getElementById('knjige').innerHTML = show;
};
So basically what I want is when I click on that button to show value of that specific book, hope I was clear..
Thanks!
You have a mis-typed value here: for(knjiga of knjigeLocalStorage){
innerHTML is going to give you all sorts of
problems with your onclick events and rendering html
I prefer to use addEventListener and adding elements via the DOM. It's a bit old school.
document.addEventListener("DOMContentLoaded", (event) => {
const div = document.getElementById('knjige');
knjigeLocalStorage.forEach((k) => {
const d = document.createElement("div");
d.classList.add("grid-card");
const text = document.createElement("div");
text.classList.add("text");
const h4 = document.createElement("h4");
h4.innerHTML = `Naziv ${k.Naziv}`;
const button = document.createElement("button");
const i = document.createElement("i");
i.classList.add("fas", "fa-shopping-cart");
button.appendChild(i);
button.addEventListener("click", () => {
alert(`Naziv ${k.Naziv}`);
});
text.append(h4);
text.append(button);
d.appendChild(text);
div.appendChild(d);
});
});
Try this fiddle:
https://jsfiddle.net/2cor9v1w/
document.addEventListener("DOMContentLoaded") Doesn't work for me with JSFiddle, but you may need it for your actual code to replace window.onload.

<li> element toggle between different background colors

I want to change the background color of the button based upon the class. Why it is not going back after second click?
var $begin1 = $(".begin1").click(function(e) {
e.preventDefault();
var buttonState = $(this).attr("class");
if (buttonState != 'pressed') {
$begin1.removeClass('pressed');
$(this).addClass('pressed');
} else {
$(this).removeClass('pressed');
$(this).addClass('unpressed');
}
});
li {
list-style-type: none;
}
.begin1.unpressed,
.begin2.unpressed {
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
li.begin1.pressed,
li.begin2.pressed {
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<li class="begin1 unpressed">
<h2>Button</h2>
</li>
https://jsfiddle.net/nrebaL00/
You can simplify your code greatly. Apply the default styling from the beginning and you don't need an .unpressed class.
The issue with using .attr( 'class' ) is that it will retrieve all the classes applied to the element as a string. Performing a check like if ( 'a' === $el.attr( 'class' ) ) won't work where $el is <li class="a b c"> as $el.attr( 'class' ) would return 'a b c' and not 'a'. Which is why your check was failing after the first click. This kind of check would be good for .hasClass().
e.prevendDefault() is not required for an <li>, so remove that.
Note: the selector I used for jQuery is pretty generic. You may need to increase it's specificity if there are other <li> on the page that don't require the functionality. Something along the lines of adding a class to the <ul> and using that as the part of the jQuery selector. i.e. <ul class="clicky-mcclickens"> and $( '.clicky-mcclickens li' ).
$('li').on('click', function(e) {
$(this).toggleClass('pressed');
});
li {
list-style-type: none;
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
.pressed {
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<h2>Button 1</h2>
</li>
<li>
<h2>Button 2</h2>
</li>
</ul>
Sometimes you need more control than simply adding/removing a class when an element is clicked. In those instances you can use .hasClass() to check if the element has the class in question and apply the appropriate action.
Your code is much more complex than it needs to be; you can just call toggleClass() like this:
var $begin1 = $(".begin1").click(function() {
$(this).toggleClass('pressed unpressed');
});
Updated fiddle
Note that e.preventDefault() is redundant for an li element as it has no default behaviour to prevent.
I would use toggleClass instead of adding and removing manually. This seems to work:
var $begin1 = $(".begin1").click( function(e) {
$begin1.toggleClass('pressed');
});
Instead of check the complete string of the class of the element you can check if the element has specific class using hasClass:
var $begin1 = $(".begin1").click( function(e) {
e.preventDefault();
if(!$(this).hasClass('pressed')){
$begin1.removeClass('unpressed');
$(this).addClass('pressed');
} else{
$(this).removeClass('pressed');
$(this).addClass('unpressed');
}
});
li{
list-style-type: none;
}
.begin1.unpressed,
.begin2.unpressed {
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
li.begin1.pressed,
li.begin2.pressed{
background: #4CAF50;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<li class="begin1 unpressed"><h2>Button</h2></li>
The problem with using the attr('class') is that you can't know what exactly will be the final string.
Just replace your js with:
$(document).ready(function() {
$(".begin1").click(function(){
$(this).toggleClass("pressed");
});
});

Using jQuery to alternate between classes upon click event

I'm feeling awfully silly here - I can't get a simple class switching statement to work in jQuery! I can only sit in frustration as for the last 45 minutes, I've searched Stack Overflow questions and answers, to no avail.
My goal is, upon clicking an item with the colorClick id (already containing a default class of "white"), to rotate that item between being assigned the class green, yellow, orange, red, and back to white again (ad infinitum).
The CSS is simple - each class simply corresponds to a different background color.
The HTML is simple - a div tag with two CSS classes (one static, one to be changed by jQuery).
The jQuery is simple - read the class on the clicked item, and change it.
And now, you understand what vexes me. Here's what I'm working with so far:
$("#colorClick").click(function () {
if ($(this).hasClass('white')) {
$(this).removeClass("white").addClass("green");
} else if ($(this).hasClass('green')) {
$(this).removeClass('green').addClass('yellow');
} else if ($(this).hasClass('yellow')) {
$(this).removeClass('yellow').addClass('orange');
} else if ($(this).hasClass('orange')) {
$(this).removeClass('orange').addClass('red');
} else if ($(this).hasClass('red')) {
$(this).removeClass('red').addClass('white');
});
.toDoItem {
text-align: left;
padding: 3px;
margin-bottom: 5px;
border: 1px solid;
border-color: #e8e7e7;
}
.white {
background-color: #ffffff;
}
.green {
background-color: #b2d8b2;
}
.yellow {
background-color: #ffffb2;
}
.orange {
background-color: #ffe4b2;
}
.red {
background-color: #ffb2b2;
}
<div class="toDoItem white" id="colorClick">To-do list item</div>
<div class="toDoItem white" id="colorClick">To-do list item</div>
<div class="toDoItem white" id="colorClick">To-do list item</div>
Link to the fiddle:
http://jsfiddle.net/andrewcbailey89/4Lbm99v0/2/
First things first, when making a list, you should use the correct list elements. Your "To Do" list fits the definition of a description list (<dl>) so you should use that instead of <div> elements.
You can save a lot of lines of code by getting rid of the classes and creating an array of colors. Make sure that the colors are in the same order that you want them to be shown. We will use this array to set the background color based on an incremented counter.
var colors = ['#b2d8b2', '#ffffb2', '#ffe4b2', '#ffb2b2', '#fff'];
You can also greatly simplify your script by using a "factory" function which defines a scope and builds an event listener function, which it returns. This creates a "safe" scope for each listener function to reside in that we can define variables which will store information between events.
In the following snippet, we define a count variable that we increment on each click. We use the incremented variables remainder when dividing by the length of the color array using the modulo operator %. If the number is smaller than the length of the array, it will return the number, otherwise it will return the remainder when dividing by the length of the array, allowing us to loop through continuously.
function todoItemListener() {
var count = 0;
return function () {
$(this).css({ 'background-color': colors[count++ % colors.length] });
}
}
Then instead of assigning the function declaration as normal (without the parenthesis), we assign the result of the factory function, simply append the parenthesis and the function will execute and return the resulting listener function. This allows us to add as many listener functions as we want, so if you're adding new todo list items, we can simply build another listener function.
$('.todo-list dd').each(function () {
$(this).on('click', todoItemListener());
});
$('.add-item').on('click', function () {
var list = this.parentNode.parentNode;
$('<dd>To-do list item</dd>').appendTo(list).on('click', todoItemListener());
});
This method also allows you to easily change the array of colors at will. So say if an option is selected somewhere on the page, another color could become available, or not available.
Also, for some extra UX goodness, I added CSS to stop selection of the text on click (that can get annoying) and to change the cursor to a pointer to give it a more actionable feel.
Here is the full demo, I've included multiple to-do lists to show that it can be done.
var colors = ['#b2d8b2', '#ffffb2', '#ffe4b2', '#ffb2b2', '#fff'];
function todoItemListener() {
var count = 0;
return function () {
$(this).css({ 'background-color': colors[count++ % colors.length] });
}
}
$('.todo-list dd').each(function () {
$(this).on('click', todoItemListener());
});
$('.add-item').on('click', function () {
var list = this.parentNode.parentNode;
$('<dd>To-do list item</dd>').appendTo(list).on('click', todoItemListener());
});
.glyphicon-plus-sign {
font-size: 15px;
}
.todo-list {
background: #efefef;
padding: 3px;
}
.todo-list dd {
margin: 0;
text-align: left;
padding: 3px;
margin-bottom: 7px;
border: 1px solid;
border-color: #e8e7e7;
background-color: #fff;
}
.add-item, .todo-list dd {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
cursor: pointer;
}
.add-item {
float: right;
margin: 4px;
}
.todo-list dh::after {
content: "";
display: block;
clear: both;
}
.todo-list dh h3 {
float: left;
margin: 0px;
max-width: 100%;
overflow: hidden;
}
/* This rule is for the demo only */
.wrp {
float: left;
width: 33.33333333%;
padding: 1px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="wrp">
<dl class="todo-list" id="todo-list-1">
<dh>
<h3 class="center" contenteditable>To Do List 1</h3>
<span class="add-item glyphicon glyphicon-plus-sign"></span>
</dh>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
</dl>
</div>
<div class="wrp">
<dl class="todo-list" id="todo-list-2">
<dh>
<h3 class="center">To Do List 2</h3>
<span class="add-item glyphicon glyphicon-plus-sign"></span>
</dh>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
</dl>
</div>
<div class="wrp">
<dl class="todo-list" id="todo-list-3">
<dh>
<h3 class="center">To Do List 3</h3>
<span class="add-item glyphicon glyphicon-plus-sign"></span>
</dh>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
<dd>To-do list item</dd>
</dl>
</div>
You are missing some quotes in a few places, and you didn't close the last if statement.
ex: $(this).hasClass(green) should be $(this).hasClass('green')
Additionally, you should change colorClick to a class rather than an ID, as there are multiple of these elements.
I also changed all of your quotes to single quotes for consistency's sake.
Here is a working snippet:
$(".colorClick").click(function () {
if ($(this).hasClass('white')) {
$(this).removeClass('white').addClass('green');
} else if ($(this).hasClass('green')) {
$(this).removeClass('green').addClass('yellow');
} else if ($(this).hasClass('yellow')) {
$(this).removeClass('yellow').addClass('orange');
} else if ($(this).hasClass('orange')) {
$(this).removeClass('orange').addClass('red');
} else if ($(this).hasClass('red')) {
$(this).removeClass('red').addClass('white');
}
});
.toDoItem {
text-align: left;
padding: 3px;
margin-bottom: 5px;
border: 1px solid;
border-color: #e8e7e7;
}
.white {
background-color: #ffffff;
}
.green {
background-color: #b2d8b2;
}
.yellow {
background-color: #ffffb2;
}
.orange {
background-color: #ffe4b2;
}
.red {
background-color: #ffb2b2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="colorClick toDoItem white">To-do list item</div>
<div class="colorClick toDoItem white">To-do list item</div>
<div class="colorClick toDoItem white">To-do list item</div>
First you are using same id for multiple elements. id should be unique for each element. You can use toDoItem class instead of colorClick id to bind click event. To get rid of complex if else statement you can put all class in an array in your required sequence. Then on click of toDoItem change class according to the sequence of array. If you reached at the last item of array then go back to first.
var colors = ['white', 'green', 'yellow', 'orange', 'red'];
var total = colors.length-1;
$(".toDoItem").click(function() {
var color = $(this).attr('class').split(' ')[1];
var index = colors.indexOf(color);
index = index==total? 0 : index+1;
$(this).removeClass(color).addClass(colors[index]);
});
.toDoItem {
text-align: left;
padding: 3px;
margin-bottom: 5px;
border: 1px solid;
border-color: #e8e7e7;
}
.white {
background-color: #ffffff;
}
.green {
background-color: #b2d8b2;
}
.yellow {
background-color: #ffffb2;
}
.orange {
background-color: #ffe4b2;
}
.red {
background-color: #ffb2b2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toDoItem white">To-do list item</div>
<div class="toDoItem white">To-do list item</div>
<div class="toDoItem white">To-do list item</div>
JS FIDDLE DEMO

Onhover of Navigation change to light color background

I am doing a functionality for my website, where I want a functionality as same here.
In detail: When I hover on navigation, I want to make the background light.
Do let me know if needed anything else.
I hope I understand your question. See the example below:
$(document).ready(function() {
$("ul li").mouseover(function () {
$(this).addClass('light-bg', 1000);
$('body').addClass('new-body-bg', 1000);
});
$("ul li").mouseleave(function () {
$(this).removeClass('light-bg', 1000);
$('body').removeClass('new-body-bg', 1000);
}); });
ul {
background-color: #ddd; /* Choose the color of your choice */
height: 40px;
}
li {
display: inline-block;
font-size: 18px;
padding: 10px;
line-height: 20px;
text-align: center;
margin-right: 15px;
}
.light-bg {
background-color: #fff; /* Choose the color of your choice */
line-height: 20px;
}
.new-body-bg {
background-color: #ccc; /* Choose the color of your choice */
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li> One </li>
<li> Two </li>
<li>Three </li>
<li> Four</li>
</ul>
It works perfectly on JsFiddle
See: http://jsfiddle.net/snlacks/tekokmke/1/
Without using jQuery,
you want to find all of the elements you want to do this to
then you want to loop through them
You'll apply two listeners to each one, one for entering and one for leaving.
js:
var mes = document.querySelectorAll(".me");
function changeIn(){
document.body.style.backgroundColor = "lightgray";
}
function changeOut(){
document.body.style.backgroundColor = "darkgray";
}
for(i = 0; i < mes.length; i++){
mes[i].onmouseenter = changeIn;
mes[i].onmouseleave = changeOut;
}

Categories

Resources