I am using some jquery code to highlight the current active page on my site. It is working great for the page. but when I am linking the menu to any div id it is not highlighting. how can I make it work for id as well.
Here is my code:
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$(".menu_holder a").each(function() {
// checks if its the same on the address bar
if (url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
I suppose that for menu you use well try this change ul.nav with your class
var url = window.location;
var element = $('ul.nav a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0;
}).addClass('active').parent().parent().addClass('in').parent();
if (element.is('li')) {
element.addClass('active');
}
cheers!!
Based on the comments, I assume that you are trying to highlight the div as well the menu clicked.
You can use the below code. It will scroll the div as well as highlight the target div as well as the menu linked clicked.
$(function() {
// this will get the full URL at the address bar
var url = window.location.href;
$(".menu_holder a").on('click',function(event) {
event.preventDefault();
var selectedDiv = $(this).attr('href');
$('html, body').animate({
scrollTop: $(selectedDiv).offset().top - 20
}, 'slow');
$(selectedDiv).addClass("active");
$(this).addClass("active");
});
});
#contact {
margin-top: 1000px;
height:50px;
width:50px;
}
.active
{
background-color : red;
color:#fff;
}
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="menu_holder">
Home
contact
</div>
<div id="contact">
contact section
</div>
</body>
Suppose you have this html:
<div class="Menu">
Div 1
Div 2
</div>
<div id="Div1">
content 1
</div>
<div id="Div2">
content 2
</div>
if you want to highligth the anchor after the click you can use this code that merges yours and adds what you are looking for:
var url = window.location.href;
$(".Menu a").each(function(e) {
if (url == (this.href)) {
$(this).addClass("Active");
}
}).on("click", function(e) {
var a = this;
setTimeout(function() {
if (window.location.href == a.href)
$(a).addClass("Active");
}, 0);
});
I used setTimeout (..., 0) to make the browser process the click and change the location.
That is because window.location.href gives you the actual, absolute URL of the page -- for example, http://stackoverflow.com/questions/38541730/highlight-active-link-on-menu#contact. But, most probably your link has an href that is relative -- basically, this.href is probably just #contact.
I think a better solution would be to use a regular expression like this to get the relative url:
window.location.href.match(/#.*/) //gives you $contact"
EDIT: Thanks to Mottie, here's an even better solution:
window.location.hash //gives you "#contact"
Related
http://jsfiddle.net/cEJtA/
$(function () {
$(".div1, .div2").hide();
$(".link1, .link2").bind("click", function () {
$(".div1, .div2").hide();
if ($(this).attr("class") == "link1")
{
$(".div1").show();
}
else
{
$(".div2").show();
}
});
});
Can anyone please help with this code.
I want 5 divs that work based on the link that's clicked, so there are 5 divs either shown/hidden.
I can do everything except the if/else statement for more divs - any help please?
Off the top of my head, you can add a data attribute on the class and use that to toggle the targeted div element.
$(function () {
$(".div1, .div2,.div4, .div3, .div5").hide();
$("a").bind("click", function () {
$(".div1, .div2,.div4, .div3, .div5").hide();
var target = $(this).data("target");
$("."+target).toggle();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Link 1
Link 2
Link 3
Link 4
Link 5
<div class="div1">I'm div1</div>
<div class="div2">I'm div2</div>
<div class="div3">I'm div3</div>
<div class="div4">I'm div4</div>
<div class="div5">I'm div5</div>
</body>
</html>
you could also get the current element's class, parse it and generate div class name off of it and use that to show/hide things. e-g
link1 => div1 (replace link with div)
Try this way
<html>
<body>
Link 1
Link 2
<div id="link1" class="commonDiv">I'm div1</div>
<div id="link2" class="commonDiv">I'm div2</div>
</body>
</html>
$(function () {
$(".commonDiv").hide();
$(".link1, .link2").bind("click", function () {
$(".commonDiv").hide();
var id = $(this).attr("class");
$('#' + id).show();
});
});
I'm attempting to create a script that, when I click a nav-link, checks what class is attached to that specific link, then hides the current page and displays the page that also contains that specific class.
This script currently switches between 2 pages rather than checking for a page with a class, but I'm sure it'll be simple to add that later (1 line of code).
(function () {
pages = ["home", "about", "portfolio", "misc", "inquire"];
//request = window.location.hash.substring(1);
//Finding page corresponding to clicked link
function SetRequest (link, pages)
{
lookingFor = ".home";
for (var i in pages)
{
if (link.hasClass(("." + pages[i]).toString()))
{
lookingFor = pages[i];
}
}
return ("." + lookingFor).toString();
}
//Hiding all other pages, showing page needed
function ShowCurrentPage (page, pages, lookingFor)
{
for (var i in pages)
{
if (page.hasClass(lookingFor))
{
$(".page.current").animate({opacity: 0});
$(".page.current").removeClass("current");
$(".page").animate({opacity: 1});
$(".page").addClass("current");
}
}
}
$(".nav-link a").click(function(){
ShowCurrentPage($(this), pages, SetRequest($(this), pages));
});
})();
You don't need to make a loop. Just do something like this:
function switchPage(lookingFor)
{
var lookingForDom = $('' + lookingFor); // I assume that lookingFor carries full selector either id or css based
if (lookingForDom.length > 0) // We've found one
{
$(".page.current").removeClass("current").animate({opacity: 0});
lookingForDom.addClass("current").animate({opacity: 1});
}
}
There's also easy way to obtain needed page name, just keep it inside some attribute of link that's beeing clicked and retrive it. Href is designed place for such things (but you need to use id on page-div then). So js would be:
$('.nav-link a').click(function(){ switchPage($(this).attr('href')); });
Also remember to registrate your events either with inside $(document).ready function like so:
$(document).ready(function()
{
$(".nav-link a").click(...);
});
Full example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
function switchPage(lookingFor)
{
var lookingForDom = $('' + lookingFor); // I assume that lookingFor carries full selector either id or css based
if (lookingForDom.length > 0) // We've found one
{
$(".page.current").removeClass("current").animate({opacity: 0});
lookingForDom.addClass("current").animate({opacity: 1});
}
}
$(document).ready(function()
{
// Initial switch to hide other pages
$('.page').css({ opacity: 0 });
switchPage('#pageA');
$('.links a').click(function(){ switchPage($(this).attr('href')); });
});
</script>
</head>
<body>
<div id="pageA" class="page">I'm page A</div>
<div id="pageB" class="page">I'm page B</div>
<div id="pageC" class="page">I'm page C</div>
<ul class="links">
<li>Go to page A</li>
<li>Go to page B</li>
<li>Go to page C</li>
</ul>
</body>
</html>
Here's a really simple code that does the trick : http://codepen.io/anon/pen/advjeN
html :
<nav class="nav-link">
<a class="aa" href="#">FIRST LINK</a>
<a class="bb" href="#">SECOND LINK</a>
</nav>
<div class="pages">
<div class="aa page red"></div>
<div class="bb page blue hide"></div>
</div>
CSS :
.page{
height: 200px;
width: 200px;
margin : 20px;
display: inline-block;
}
.red{ background-color: red;}
.blue{background-color: blue;}
.hide{ display: none;}
and jquery :
(function () {
$(".nav-link a").click(function(){
var myclass = '.' + $(this).attr('class');
$('.pages').children().hide();
$(myclass).fadeIn();
});
})();
If put them all in a " pages " div so you can hide them all easely, but if they all at least one class that's the same for all you can simply do $(myclass).hide();
I have a webpage which is a huge form (6 pages long). In order to make it more user friendly, I decided to break this down into different sections (div tags).
I have placed Previous and Next button on page. On previous click it should display the previous div tag I was at and next should display the next div tag. I was wondering what would be the best way to implement it? So far I have this function which I know is hardcoded for div tag called GeneralSection. Just like GeneralSection, I have 20 more sections. Any ideas how should I go about it ? Help appreciated! :)
$(document).ready(function () {
$("#imgNext").click(function () {
$("#GeneralSection").hide();
});
});
You could just iterate through an array of elements.
Here's a simple JSBin that should get you going: https://jsbin.com/siyutumizo/edit?html,js,output
$(document).ready(function() {
var $steps = $('.step');
var currentStep = 0,
nextStep;
$steps.slice(1).hide(); //hide all but first
$('#next').on('click', function(e) {
e.preventDefault();
nextStep = currentStep + 1;
if (nextStep == $steps.length) {
alert("You reached the end");
return;
}
$($steps.get(currentStep)).hide();
$($steps.get(nextStep)).show();
currentStep = nextStep;
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="wizard">
<div class="step">1</div>
<div class="step">2</div>
<div class="step">3</div>
<div class="step">4</div>
<div class="step">5</div>
<div class="step">6</div>
</div>
<button id="next">Next</button>
</body>
</html>
Another way of implementing this is through siblings.
Jsbin: https://jsbin.com/tarajuyusu/edit?html,js,output
$(function() {
$('div#GeneralSection').slice(1).hide(); // hide all section, except for first one
$('#imgNext').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].nextElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].nextElementSibling).show();
});
$('#imgPrev').on('click', function() {
var section = $('div#GeneralSection').filter(':visible');
if ($(section[0].previousElementSibling).attr('id') != "GeneralSection")
return;
section.hide();
$(section[0].previousElementSibling).show();
});
});
Give each section class pages and per section ids page-1, page-2 like that
$(document).ready(function () {
var pages = $(".pages").length;
$("#imgNext").click(function () {
var nextPageNo = parseInt($(".pages:visible")[0].id.split('-')[1])+1;
if(nextPageNo > pages)
return false;
$(".pages:visible").fadeout();
$("#page-"+nextPageNo).fadeIn();
});
});
Havent fully tetsted but this should get you going.
Update
HTML
<div id="container">
<div id="page-1" class="pages">1</div>
<div id="page-2" class="pages">2</div>
<div id="page-3" class="pages">3</div>
<div id="page-4" class="pages">4</div>
<div id="page-5" class="pages">5</div>
<div id="page-6" class="pages">6</div>
</div>
CSS
.pages{
display: none;
}
#page-1{
display: block;
}
I'm looking at running this script:
$(document).ready(function() {
$('a').click(function(e) {
var urlyep=(this)
e.preventDefault();
$("#content").load($(urlyep).attr('href'));
});
});
This loads content from a local HTML file via a menu hyperlink into the #content div. It works great but I want to make it more specific so it only works when the click is made in the #menubar div.
Err… You mean $('#menubar a').click(…) ?
<script type="text/javascript">
$(document).ready(function() {
$('#menubar a').click(function(e) {
var urlyep=(this)
e.preventDefault();
$("#content").load("yourexternalpage.html");
});
});
</script>
<div id="content" >new content will go here</div>
<div id="menubar" >menubar</div>
If you have more than one link on the menu bar, I am assuming you have, each needing to load it's own content/page you could do something like the following.
<script type="text/javascript">
$(document).ready(function() {
$('#menubar a').click(function(e) {
var urlyep=(this.name);
e.preventDefault();
$("#content").load(urlyep);
});
});
</script>
<div id="content" >new content will go here</div>
<div id="menubar" ><a href="#" name="page1.php" >menubar link1</a>-<a href="#" name="page2.php" >menubar link2</a></div>
I'm creating a page with an image at the top, and a menu below. When the user clicks on on of the 3 menu buttons, the image slideUp and the page scrolls down so the menu is at the top of the page, then the right .content div fades in. The slideUp should only happen the first time the user clicks on of the buttons.
What the absolute best way to do this with jQuery? (no plugins)
I also need to know how I can't prevent it to fade in the page that is already visible if i click the same button twice?
I'm using rel instead of href, since the href made the page jump, even with return false.
This is what I have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
imgVisible = true;
$('#mainmenu a').click(function(){
var $activeTab = $(this).attr('rel');
if(!imgVisible){
$('html:not(:animated),body:not(:animated)').animate({scrollTop:$('#mainmenu').offset().top-20},500);
$('.content').hide();
$($activeTab).fadeIn();
} else{
$('#imgholder').slideUp(500,function(){
imgVisible = false;
$('#mainmenu a[rel="'+$activeTab+'"]').click();
});
}
return false;
});
});
</script>
<div id="imgholder"><img src="image.jpg" /></div>
<div id="mainmenu">
<ul>
<li><a rel="#tab1"></a></li>
<li><a rel="#tab2"></a></li>
<li><a rel="#tab3"></a></li>
</ul>
</div>
<div id="container">
<div class="content" id="tab1">
content
</div>
<div class="content" id="tab2">
content
</div>
<div class="content" id="tab3">
content
</div>
</div>
The following code accomplishes what you need:
$('#mainmenu a').click(function(){
var myrel=$(this).attr('rel');
$('.content:not([id='+myrel+'])').hide();
$('#imgholder').slideUp(500,function(){
$('#'+myrel).fadeIn();
});
});
....
<li><a href='#' rel='tab0'></a></li>
I have removed the '#' sign from your rel='' piece ;-)
I am not sure why you would want to scroll the page. When a user clicks on the menu, he/she already has it focused (so it is visible inside the current viewport). But do you have a very large top image? If that is the case, let me know and I will modify the snippet. (Still, it depends on the amount of content below the menu visible when the page first loads.)
Also, for SEO reasons you might want to use the href instead of the rel attribute and create separate content holding pages. The following snippet would remove the navigation action.
$('#mainmenu a').each(function(){
var myhref = $(this).attr('href');
$(this).attr('href','#').attr('rel',myhref);
}).click(function(){
var myrel=$(this).attr('rel');
$('.content:not([id='+myrel+'])').hide();
//....etc
I think this is a great example of what your looking for: Organic Tabs
var imgVisible = true;
var $activeTab, $lastTab;
var $mainmenu = $('#mainmenu');
var offset = $mainmenu.offset().top - 20;
$mainmenu.find('a').click(function() {
$activeTab = $($(this).attr('rel'));
if (!imgVisible) {
// dont fire any events if already open
if ($lastTab.attr('id') == $activeTab.attr('id')) return false;
$lastTab.fadeOut('normal', function() {
$activeTab.fadeIn(500, function() {
$lastTab = $activeTab;
});
});
} else {
$('#imgholder').slideUp(500, function() {
imgVisible = false;
window.scrollTo(0, offset);
$activeTab.fadeIn(500, function() {
$lastTab = $activeTab;
});
});
}
return false;
});
I highly suggest adding <a href="#"> as this will not make the page jump when done properly and will ensure validation on your anchor links. Someone let me know if I missed something, it can be resolved quickly (or you can do it for me if you have an optimization or improvement).