When visit a page, add class to div and save in cache - javascript

How can I add a class to a div when I visit a page in my website and save this on cache?
For example: I have a index.html that looks like this: https://i.stack.imgur.com/6iJEr.png
What I wanna do is when someone click in one div (witch is linked to a page like page3.hml) this div will add a class and save in cache, so when back to index.html this div will still have this class. Like this: https://i.stack.imgur.com/lMjZG.png
The class wold be something like
.visited{
border-bottom: 10px solid red;
}
Is this possible?
Sorry for my English :(

You can use local storage to save the divs. With my example, each div needs a different ID and a click handler added to a class.
SO Snippets doesn't allow local storage so here is a working fiddle: https://jsfiddle.net/hdo4sq9j/2/
.visited{
border-bottom: 10px solid red;
}
<div id="id1" class="clickme">1</div>
<div id="id2" class="clickme">2</div>
<div id="id3" class="clickme">3</div>
visited = localStorage.getItem('visited')
if (visited === null) {
localStorage.setItem('visited', []);
visited = [];
}
else{
visited = visited.split(",")
}
divs = document.querySelectorAll(".clickme");
divs.forEach(function(div) {
div.addEventListener("click", function(ev) {
if (visited.indexOf(div.id) == -1) {
visited.push(ev.target.id)
}
localStorage.setItem('visited', visited);
})
if (visited.indexOf(div.id) > -1) {
div.classList.add("visited")
}
});

The simplest method would be using the CSS :visited selector if you won't mind converting those divs into hyperlinks.
Then it would be something like:
a:visited {
border-bottom: 10px solid red;
}
Check out the w3schools article about the hyperlink selectors:
https://www.w3schools.com/css/css_link.asp

Related

Cycle through 2 classes on `html` after clicking a link/toggle

I currently have a toggle that when clicked adds/removes a class to the html tag.
I'd like to update this so if you click after the original class is added the class is changed to .new-mode rather than removing the current class and the html tag being class-less. If the link is clicked again, it will then return to the default state.
So in essence it's got 3 states:
No class (default / on load)
Class One added (on 1st click)
Class One removed, Class Two added (on 2nd click)
Then on the next click it would return to the default state without a class. So essentially just cycling through 2 classes on click. You can see I have the 1st toggle working in my example - but I'm unsure how to target the next click(s) and I'd really appreciate some help.
const html = document.querySelector('html');
const button = document.querySelector('.contrast__link');
button.addEventListener('click', e => {
e.preventDefault();
html.classList.toggle('dark-mode');
});
html { background: white; color: black; }
.dark-mode { background: black; color: white;}
.new-mode { background: blue; color: white;}
<p class="contrast__link">Click here</p>
Check what the current state is and handle the transition to the next state. Since you have a reference to the html element, you can use its classList property to see which classes are currently applied to it.
The return value is not an array, it's a DOMTokenList, so be sure to use DOMTokenList.contains() instead of Array#includes. The collection also supports adding, removing, and toggling one or more classes.
The simplest way to check and change the state is an if-else chain:
const html = document.querySelector('html');
const button = document.querySelector('.contrast__link');
button.addEventListener('click', e => {
e.preventDefault();
if (html.classList.contains('dark-mode')) {
html.classList.remove('dark-mode');
html.classList.add('new-mode');
}
else if (html.classList.contains('new-mode')) {
html.classList.remove('new-mode');
}
else {
html.classList.add('dark-mode');
}
});
html { background: white; color: black; }
.dark-mode { background: black; color: white;}
.new-mode { background: blue; color: white;}
<p class="contrast__link">Click here</p>

Cycle through css stylesheet files by clicking single div with javascript

I want to swap the CSS stylesheet file without reloading the page. I'm wondering how to cycle through an array of multiple stylesheets by clicking a single source (div, #button), returning to the default, and then continuously looping through the list. It would also be great if the browser could remember what stylesheet the website is currently on for page to page continuity, though this is not necessary. The following is what I have so far...
HTML:
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<div id="button" style="width: 100px; height: 100px; background-color: red;"></div>
Javascript:
var stylesheets = [
"style1.css",
"style2.css",
"style3.css",
"default.css"
];
function swapStyleSheet(sheet){
document.getElementById('pagestyle').setAttribute('href', sheet);
}
One way to do so would be to shuffle the list of stylesheets and render the first one every time:
function nextSytlesheet() {
stylesheets.push(stylesheets.shift());
swapStyleSheet(stylesheets[0]);
}
But, what are you trying to achieve by reloading styles? Every CSS file initiates a GET request to the server, so unless your styles are huge it makes more sense to have one stylesheet per app and dynamically switch classes instead. To simulate the full stylesheet swapping, you can just prepend .style1 (with trailing space) class to every rule you have in style1.css, do the same for others, and then switch these classes on <body> instead of reloading stylesheets.
Not sure what your purpose is, but you could just change the class names of elements on the page via a button, and have different styles associated with the classes in your main stylesheet.
Hope this helps! ;)
Edit: Just as Igor said. I didn't see his whole comment till now.
Edit 2: Sorry for the late response, but I was able to make a demo for you!
HTML:
<div id="fakeBody" class="normal">
<p>Hello There! I change colors!</p>
<button id="button">Click me to change colors</button>
</div>
CSS:
.normal, button {
color: default;
background-color: default;
}
.light, .light button {
color: #0000ff;
background-color: #ffffff;
}
.dark, .dark button {
color: #ffffff;
background-color: #000000;
}
.wood, .wood button {
color: #444444;
background-color: #dbcc48;
}
.textEditor, .textEditor button {
color: #00ff00;
background-color: #000000;
}
Javascript:
var body = document.getElementById("fakeBody"),
themePosition = 0,
maxThemePosition = 4;
document.getElementById("button").addEventListener("click", function(){
themePosition++;
if (themePosition > maxThemePosition) {
themePosition = 0;
}
if (themePosition == 0) {
body.className = "normal";
} else if (themePosition == 1) {
body.className = "light";
} else if (themePosition == 2) {
body.className = "dark";
} else if (themePosition == 3) {
body.className = "wood";
} else if (themePosition == 4) {
body.className = "textEditor";
}
});
Working Jsfiddle

Change url doesn't change tab selected

I was implementing that if i refresh the page, it should make active to previously selected tab(preserve selected tab) . So I Create a simple html page and add some jQuery.
But if i change URL manually like file:///home/2.html#news to file:///home/2.html#home
it changes only content of page but doesn't change tab ,that was selected. .
Here is my code.
<body>
<ul>
<li id="first">Home</li>
<li id="second">News</li>
<li id="third">Contact</li>
<li id="forth">About</li>
</ul>
<p id="home">
home section
</p>
<p id="news">
news section
</p>
<p id="contact">
contact section
</p>
<p id="about">
about section
</p>
</body>
<style>
p{
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
if(localStorage.getItem("active_state") == null ){
activeStateId = "first";
}
else{
activeStateId = localStorage.getItem("active_state")
}
$('#'+activeStateId).addClass('active');
$('li').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
localStorage.setItem("active_state", $(this).attr('id'));
});
});
</script>
When you got link hashes, you dont actually reload the page, but the browser just triggers those links. You rely on CSS :target change rule which evaluates every time the #hash changes on the url.
p {
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
Thus, you have all the sections updated properly even without refreshing the page. In order to have such functionality, you don't need to store any data to the local or remote machine since you are using hashes on the url. Just use the hashes and handle the hashchange event to add the .activate class to the links like this:
$(document).ready(function() {
var hash = window.location.hash;
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
$(window).on('hashchange', function() {
$('.active').removeClass('active');
var hash = window.location.hash
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
});
});
Check my working example here: http://zikro.gr/dbg/html/urlhash.html#about

Add to Favorites Array

What I want to do in Javascript/Jquery is be able to click a button (a button on each item), that adds it to an array. This array will then be posted in order when you click on a favorites page.
I'm just having a hard time wrapping my head around how this would work. Because I may want each item in the array to contain a few things, such as a picture and text describing the item.
In general terms/examples, how would this be set up?
There are a number of ways to do this. But, I'll go with one that's a bit more general - which you can extend for yourself:
http://jsfiddle.net/TEELr/11/
HTML:
This simply creates different elements with the favorite class - which will be the selector by which we check if an element has been clicked.
<div class="favorite"><p>Add to favorites</p></div>
<div class="favorite type2"><p>Just another favorite type</p></div>
<button id="reveal">
Reveal Favorites
</button>
JS:
Every time an element with the "favorite" CSS class is clicked, it is added to the array - this also works for elements with more than one class (that have the "favorite" CSS class).
Now, when the "Reveal Favorites" button is clicked, it will alert what's in the array - which is in the order clicked (as asked).
$(document).ready(function() {
var favorites = [];
var counter = 0;
$('.favorite').click(function() {
++counter;
favorites.push("\"" + $(this).text() + " " + counter + "\"");
});
$('#reveal').click(function() {
alert(favorites);
});
});
CSS:
Simple CSS that only exist for demonstration purposes to prove previous point with multiple CSS class selectors:
.favorite {
width: 400px;
height: 50px;
line-height: 50px;
text-align: center;
display: block;
background-color: #f3f3f3;
border-bottom: 1px solid #ccc;
}
.favorite.type2 {
background-color: #ff3;
}
.favorite:hover {
cursor:hand;
cursor: pointer;
}

javascsript : adding plus/minus icon to spry collapsible panel in dreamweaver

I'm working on modifying a website which has a chart of FAQs which have has a question link.
If question link is clicked, it reveals the answer in a drop down.
My goal is to swap out a plus icon image with a minus icon next to the linked text for the drop down reveal action.
the FAQs use Spry Collapsible Panel (sprycollapsiblepanel.js) to manage the show/hiding from the link. before I go about modifying the code in the javascript source code, I was wondering if there was an easier way of doing this through dreamweaver someone might be aware of.
thanks in advance.
UPDATE:
the html calling the show/reveal actions are:
<div class="CollapsiblePanel">
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="1">Fax to E-Mail</div>
<div class="CollapsiblePanelContent">Here is the text content as it relates to Fax to E-Mail</div>
</div>
</div>
The construct the actions for the drop down, Spry requires the following at the bottom of the page:
<script type="text/javascript">
var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel1", {contentIsOpen:false});
var CollapsiblePanel2 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel2", {contentIsOpen:false});
var CollapsiblePanel3 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel3", {contentIsOpen:false});
</script>
In SpryCollapsiblePanel.css, amend the following style rules:
.CollapsiblePanelTab {
font: bold 0.7em sans-serif;
background-color: #DDD;
border-bottom: solid 1px #CCC;
margin: 0px;
padding: 2px 2px 2px 25px;
cursor: pointer;
-moz-user-select: none;
-khtml-user-select: none;
}
This increases the padding on the left to make room for the image.
Then add the images to the following rules:
.CollapsiblePanelOpen .CollapsiblePanelTab {
background-color: #EEE;
background-image: url(images/plus.gif);
background-position:left top;
background-repeat: no-repeat;
}
.CollapsiblePanelClosed .CollapsiblePanelTab {
background-image: url(images/minus.jpg);
background-position:left top;
background-repeat: no-repeat;
/* background-color: #EFEFEF */
}
THe plug ins adds a class to each panel title when is opened and when is closed, these are "CollapsiblePanelOpen" and "CollapsiblePanelClosed" accordingly. With that you can use CSS to add the +- effect with a background image perhaps.
onclick switch an image then onclick of something else switch back to + sign
If it's an image, and you don't want to change the source code, and you want to use javascript, you'll need to change the src property of the image.
// Grab the img object from the DOM
var img = document.getElementById("theImageId");
// If it's the plus pic, switch for minus, and vice versa.
if(img.src == "plus.png") {
img.src = "minus.png";
}
else {
img.src = "plus.png";
}
You can put this code in wherever you need (in an onclick or a function or whatever). Also, the URLs for the images will obviously need to be updated.
Easy fix with some simple JavaScript.
Add the following script:
<script type="text/javascript">
<!--
function name ()
{
var img = document.getElementById("imgid");
if (img.src == "plus.png") {
img.src = "minus.png";
}
else {
img.src = "plus.png";
}
}
//-->
</script>
When that's done look at the div defining the collapsible panel. It looks something like this:
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="0">Name <img src="url.com/minus.png" id="imgid"></div>
<div class="CollapsiblePanelContent">content</div>
All you need for this to work is to add onclick="name();" to the syntax:
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="0" onclick="name();">Name <img src="url.com/minus.png" id="imgid"></div>
<div class="CollapsiblePanelContent">content</div>

Categories

Resources