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
Related
I am a beginner in programming and also I am new to this community, I hope you can help me with my question.
I want to know how to redirect from page 1 to page 2 and, after that, immediately call an event of this page 2.
This is the code from page 1:
<!DOCTYPE HTML>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
/*it doesn't work (i dont know why)*/
$(document).ready(function recargar2() {
$("#chiclayo_p").trigger("onclick");
});
/*it doesn't work (i dont know why)*/
$(document).ready(function recargar3() {
$("#trujillo_p").trigger("onclick");
});
</script>
</head>
<body>
Option 1
<br>
Option 2
<br>
Option 3
</body>
</html>
This is the code from page 2:
<!DOCTYPE html>
<html>
<head>
<title>Page2</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js">
</script>
<script>
$(function () {
$('.filter').click(function () {
$(this).addClass('active').siblings().removeClass('active')
let valor = $(this).attr('data-nombre');
if (valor == 'lima') {
$('.lima').show('1000');
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
} else {
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
}
});
});
</script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'open sans';
background: #fff;
}
.botones li {
display: inline-block;
text-align: center;
margin-left: 20px;
margin-bottom: 20px;
padding: 6px 12px;
border: 1px solid blue;
list-style: none;
color: blue;
}
.botones li:hover {
background: yellow;
color: red;
cursor: pointer;
}
.botones .active {
background: rgb(158, 218, 158);
}
.galeria {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
overflow: hidden;
}
</style>
</head>
<body>
<div class="botones">
<ul>
<li class="filter active" data-nombre='lima' id="lima_p">Lima</li>
<li class="filter" data-nombre='chiclayo' id="chiclayo_p">Chiclayo</li>
<li class="filter" data-nombre='trujillo' id="trujillo_p">Trujillo</li>
</ul>
</div>
<div>
<div class="galeria" id="options">
<div class="contenedor lima">
<h1> This is the option 1 - Lima!!!</h1>
</div>
<div class="contenedor chiclayo" style="display: none">
<h1> This is the option 2 - Chiclayo!!!</h1>
</div>
<div class="contenedor trujillo" style="display: none">
<h1> This is the option 3 - Trujillo!!!</h1>
</div>
</div>
</div>
</body>
</html>
What I can't find how to solve is that when I click on option 2 on page 1, in addition to opening page 2, it should show me the selected option "Chiclayo" and the self content of this option; I would like the same thing to happen when clicking on option 3 on page 1, which should select the option "Trujillo" and show me its content. I have tried with the "onclick" event but I have not obtained results, I do not know if it is the correct way or there are better options; maybe with javascript or jquery code. I appreciate you could help me with my query.
First, as you called it on Page 2, you need to implement jQuery on Page 1.
Page 1 also needs to be called. For the jquery script codes that you write to work.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js">
for redirect;
$( "#other" ).click(function() {
window.location = "/Page2.html#chiclayo_p";
});
You can pass the option Id as query parameter in click function of a button like this on page 1
<a onclick="recargar('lima_p');">Option 1</a>
<br>
<a onclick="recargar('chiclayo_p');">Option 2</a>
<br>
<a onclick="recargar('trujillo_p');">Option 3</a>
then redirect the page 1 to page 2 to pass this value like this
function recargar(option) {
window.location.href = "page2.html" + "#" + option;
}
On page 2 you can fetch this query parameter and highlight the selected option and display related content, like this
// Add function body -- <body onload="onload()">
function onload() {
var option = window.location.hash.substring(1);
var element = $("#" + option);
alert(element);
highlightDiv(element);
}
function highlightDiv(option) {
$(option).addClass('active').siblings().removeClass('active')
let valor = $(option).attr('data-nombre');
if (valor == option) {
$('.lima').show('1000');
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
} else {
$('.contenedor').not('.' + valor).hide('1000');
$('.contenedor').filter('.' + valor).show('1000');
}
}
$(function () {
$('.filter').click(function () {
highlightDiv(this);
});
});
What you can do is pass the selected option as a query parameter and then redirect from page 1 to page 2. Then, on ready event of page 2, you can read the query parameter being passed and display your div accordingly.
Basing on this question, you can do that by using either cookies or local storage, query parameter.
As Fizer Kahn said in his answer, the most recommended way is query parameter.
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
I'm new to HTML/CSS/JS and I'm doing some testing and fiddling around with stuff and decided to highlight a nav element when on that page. I decided to use jQuery for this because from what I read it was the easiest solution. It's worked great so far, but my issue is that it doesn't highlight the main "chat" page on load because it's just the url, without the /index.html. I'd appreciate any help on how to get it to add the active class to the index.html element on load.
HTML:
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
JQuery:
jQuery(function($) {
var path = window.location.href;
$('aside nav ul li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
SCSS:
.active {
border-right: 10px solid $accent-two;
}
First, your pathname includes the entire URL, so it will never match with href in your a tag. You need to get just the page name.
Next, you should check for the href attribute of the a tag and not the href itself.
The example below uses a dummy link to aid as a demo. I had to add in the href in JS because of the snippet.
jQuery(function($) {
var path = window.location.pathname;
var page = path.split("/").pop();
//
// The line below is for demo on stackoverflow purposes
$("#forDemoOnStackPurpose").attr("href", page);
//
$('aside nav ul li a').each(function() {
if ($(this).attr("href") === page) {
$(this).addClass('active');
}
});
});
.active {
border-right: 10px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li><a id="forDemoOnStackPurpose" href="">This test page</a></li>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
I give you an example of how i will dot it. Note that i had to simulate location change with some code, but every time you run the example, it will highlight a different anchor tag.
$(document).ready(function()
{
// Simulate change on "windows.location.href"
//===========================================================
var paths = ["/index.html","/friends.html","/settings.html"];
var idx = Math.floor(Math.random() * 3) + 0;
console.log("Random idx = " + idx);
//===========================================================
var path = paths[idx];
//var path = window.location.href;
$("a").removeClass('active');
$("a[href='" + path + "']").addClass('active');
});
.active {
border-right: 10px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
I'm struggling to make a replica of the effect seen here: https://tu-dresden.de/if you click on Language, Search, Internal and the navigation in the blue header.
I have managed to create this: https://jsfiddle.net/06tfufo6/2/
I would like to keep the slideToggle effect upon clicking and somehow slideToggle each element inside.
Upon clicking the same/active button it should all close. I can't seem to wrap my head around how this can be done.
Thank you
jQuery('.container-box, .slideout-container').hide();
jQuery('.btn-group a').on('click', function() {
var target = "#" + jQuery(this).data("target");
jQuery('.slideout-container').slideToggle();
jQuery('.container-box').not(target).hide().attr('aria-expanded', 'false');
jQuery(target).show().attr('aria-expanded', 'true');
});
.btn-group {
background-color: #002557;
}
a {
color: #fff;
padding: 10px 20px;
}
.slideout-container {
padding: 25px 0;
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
Show language
Show search
Search navigation
</div>
<div class="slideout-container">
<section id="top_search" class="container-box" aria-expanded="false">
Section search
</section>
<section id="language" class="container-box" aria-expanded="false">
Section language
</section>
<section id="navigation" class="main-navigation container-box" role="navigation" aria-expanded="false">
Navigation
</section>
</div>
Store the current content in a variable and compare each time is clicked to slide down and up the content, would be something like this:
jQuery('.container-box, .slideout-container').hide();
var current_page,
target = '';
jQuery('.btn-group a').on('click', function () {
var target = "#" + jQuery(this).data("target");
if(current_page === target){
jQuery('.slideout-container').slideUp();
current_page = '';
}else{
jQuery('.slideout-container').slideDown();
current_page = target;
}
jQuery('.container-box').not(target).hide().attr('aria-expanded', 'false');
jQuery(target).show().attr('aria-expanded', 'true');
});
here is working: https://jsfiddle.net/06tfufo6/8/
For the functionality you described, you need to be able to keep track of the initiating element, and then only call your toggle code when the instigating element is clicked (assuming I understood what you were going for). The code below does just that.
You're going to need to tweak the aria-expanded true/false portion of your code, but this should get you going.
jQuery('.container-box, .slideout-container').hide();
jQuery('.btn-group a').on('click', function() {
var target = "#" + jQuery(this).data("target");
let $target = jQuery(this);
// If no other elements have instigator class, add to target
if (!jQuery(".btn-group a.instigator").length) {
$target.addClass("instigator");
}
if ($target.hasClass("instigator")) {
jQuery('.slideout-container').slideToggle();
jQuery(target).show().attr('aria-expanded', 'true');
} else {
jQuery('.container-box').not(target).hide().attr('aria-expanded', 'false');
jQuery(target).show().attr('aria-expanded', 'true');
}
});
Here's a working fiddle.
Have successfully setup a menu which cycles between multiple tabs using Javascript. The issue is I'm using SiteLevel as a search for this site. I want the search box to be a part of the hide/unhide menu but the script (I've also tried the html code for the search box, but still no fix)
I've paired it down to the simplest form of this concept to ensure that it's not some other css or script that's conflicting, but it still opens to a blank box here's the code.
I've pumped it into http://jsfiddle.net/Split98/A3DVa/
Software
Hardware
Supplies
Contact
Search
<div id="nav">
<div id="software">Hello!</div>
<div id="hardware">Yes!</div>
<div id="supplies">Yeee Haw!</div>
<div id="contact">Bingo!</div>
<div id="search"><script type="text/javascript" src="http://www.sitelevel.com/javabox?crid=ze32uipb"></script></div>
</div>
CSS:
#nav div {
display: none;
background-color: red;
height: 200px;
}
jQuery:
$(function(){
var divs = $('#nav div'),
links = $('a');
links.click(function () {
$(this.hash).toggle().siblings().hide();
return false;
});
})
Thanks in advance guys!
LIVE DEMO
Simply use #nav > div in your CSS
Will target only the immediate childrens.Otherwise all DIV elements will be hidden (your search tool)
#nav > div {
display: none;
background-color: red;
height: 200px;
}
edited jQuery
$(function () {
var divs = $('#nav div'),
links = $('a');
divs.eq(0).show(); // if you need it.....
links.click(function ( e ) { // e = event
e.preventDefault(); // instead of return false;
$(this.hash).toggle().siblings().hide();
});
});