I have created one page where that page contained the menu bar as tabs.
My url is mydomain.com/UI/ID=2?#about
Where with respective # the other tabs are there like photo,comment and setting.
When i reload any other tab like mydomain.com/UI/ID=2?#comment it going to about tab fraction of seconds then again it will come back to respect comment section.
Here is my code
<script type="text/javascript">
$(document).ready(function() {
$(".menu_content").hide();
var tabvalue=document.location.hash;
var activetab=$(this).find("a").attr("href")
$(".menu_content"+tabvalue).show();
//$(".menu_content:first").show();
$("ul.menu li:first").addClass("active");
$("ul.menu li").click(function() {
var activeTab = $(this).attr("rel");
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".menu_content").hide();
$("#"+activeTab).fadeIn();
});
var firstLi = $("ul.menu li:first").attr('rel');
if('#' + firstLi !== tabvalue) {
$("ul.menu li:first").removeClass('active');
$('li[rel="'+tabvalue.substring(1)+'"]').addClass('active');
}
});
</script>
where menu_content is class name for all tabs.
Can any one guide me how to resolve this problem.
It sounds like you're running this code after the entire page has loaded therefore you're getting a flash while the HTML is rendered in it's default state, and then to the changed version once the code executes.
The nicest way to do this would be to not use a hash for this, rather have the page in the URL i.e. mydomain.com/UI/?ID=2&page=about and use server side code to render it correctly first time, and then update the url using history.pushState in JavaScript.
But if this is all a JavaScript based page, then I would say the easiest way would be to have all of the tabs 'inactive' by default, and then only add the 'active' class when you load the page (either to the hash value, or 'about' by default).
Example:
Style
<style type="text/css">
.menu_content .panel {
display:none;
}
</style>
Script
<script type="text/javascript">
$(document).ready(function() {
//if there's a hash, get it but remove the hash, or use 'about' as a default
var selectedTab = document.location.hash ? document.location.hash.replace("#", "") : "about";
$("li#" + selectedTab).addClass("active");
$("#" + selectedTab + "_panel").show();
$("ul.menu li").on('click', function() {
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".panel").hide();
$("#" + $(this).attr("id") + "_panel").show();
});
});
</script>
HTML
<ul class="menu">
<li id="about">About</li>
<li id="comment">Comment</li>
<li id="contact">Contact</li>
</ul>
<div class="menu_content">
<div id="about_panel" class="panel"></div>
<div id="comment_panel" class="panel"></div>
<div id="contact_panel" class="panel"></div>
</div>
Related
I want every li tag to show the a's clicked href content below that li tag in a div. For example, I have a structure like this:
<ul id="ids">
<li class="res"><a class="item">item1</a></li>
<li class="res"><a class="item">item2</a></li>
<li class="res"><a class="item">item3</a></li>
</ul>
Dynamically if a's href is clicked, accordingly a function that shows the div <div class="testing"><h3>showing item1 here</h3></div> outside the <a> tag needs to be shown. That function could take time so until then Loading... needs to be shown. But I am unable to detect where the user has clicked as class names are the same. Once loading is done, loading should be hidden.
So far I have this:
$(document).on('click', '.item', function(e) {
e.preventDefault();
$(this).append('Loading');
//function code here
$(this).append('<div class="testing"><h3>showing item1 here</h3></div>');
});
Also, the function appends 1 div tag with class 'mydiv', that needs to be hidden. But again, since class names that get appended to every <li> is the same, I don't know where the click has taken place to detect it.
to summarise:
show a list of elements which has anchor tag
click on every element should show the content of the click in a div under that anchor tag
content of anchor tag can take 2 seconds so until then user should see "loading". Once it loads, loading should be hidden
You are looking for $.after() or $.insertAfter():
$(document).on('click', '.item', function(e) {
e.preventDefault();
var aTag = $(this);
if (aTag.siblings('.testing, .loader').length === 0) { //it's not loaded or loading
var loader = $('<div class="loader">Loading</div>');
loader.insertAfter(aTag);
//function code here
loader.remove();
aTag.after('<div class="testing"><h3>showing ' + aTag.html() + ' here</h3></div>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ids">
<li class="res"><a class="item">item1</a>
</li>
<li class="res"><a class="item">item2</a>
</li>
<li class="res"><a class="item">item3</a>
</li>
</ul>
If you want to avoid multiple loadings check if it exists before:
if(aTag.siblings('.testing, .loader').length === 0){ //it's not loaded or loading
}
You can get the href attribute using `$(this). This should work.
$(document).on('click', '.item', function(e) {
e.preventDefault();
var href = $(this).attr("href");
$(this).append('Loading');
$(this).append('<div class="testing"><h3>showing ' + href + ' here</h3></div>');
});
Also, the code above will append the div inside the a tag. You probably want to put it somewhere else using something like
$("#messageDiv").html('<div class="testing"><h3>showing ' + href + ' here</h3></div>');
To hide the loading message, you can wrap that in a span
$(this).append('<span class="loadingspan">Loading</span>');
Then in the code that runs when the load is complete, you can use
$('.loadingspan').hide();
I am trying to do something different without knowing if it is a good idea or not
I have a navigation menu as the following:
...
<li>Home</li>
<li>FAQ</li>
<li>Contact</li>
...
I do not want to use a server-side scripting because it takes more time to make db connection and define some configuration, and not want to multiply the pages for each one. So I made a master page index.php
in body section
there are two elements:
an h3 element to display the page title and a div to display the content which is called from another html source.
...
<div class="container">
<h3 id="pageTitle"></h3>
<div id="pageContent"></div>
</div>
...
I am using jQuery's click event to load the page into the div
$(function() {
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html"); //removing # char.
});
});
It works fine. But when I press F5 it returns the initial state as normal. How can I load the current page by referencing the address bar (I can see eg. sitename/#mfaq) when page is refreshed.
I think, first I need to detect if page is refreshing and load the corresponding html file in according to the #m**** on the addressbar.
$(function() {
$("a[href^='#m']").click( function(evt) {
// ------ This should work
// renamed parameter elem to evt like corrected in comment
evt.preventDefault();
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
Add to your DOM ready function:
if (window.location.hash != "") {
$("#pageTitle").text($("a[href='"+window.location.hash+"']").text());
$("#pageContent").load(window.location.hash.slice(1) + ".html");
}
I have made this. It works well. But I am not sure about performance issues:
$(function() {
var address = $(location).attr('href');
var hash = address.lastIndexOf("#");
var page = address.substring(hash+1);
if (hash < 1)
{
$("#pageContent").load("mhome.html");
$("#pageTitle").html("Default Page Title");
}
else
{
$("#pageContent").load(page + ".html");
$("#pageTitle").html($("a[href='" + address.substring(hash) + "']").text());
}
$("a[href^='#m']").click(
function() {
$("#pageTitle").text($(this).text());
$("#pageContent").load($(this).attr("href").substring(1) + ".html");
});
});
I'm trying to set accordion menu "active" after click on link and change the page...
<div class="menu">
<dl>
<dt>HOME</dt>
<dt>QUEM SOMOS</dt>
<dd>
<ul>
<li>EMPRESA</li>
<li>INSTITUCIONAL</li>
<li>NOSSOS PRODUTOS</li>
<li>RESPONSABILIDADE SOCIAL</li>
<li>RESPONSABILIDADE AMBIENTAL</li>
</ul>
</dd>
<dt>PRODUTOS</dt>
<dd>
<ul class="produtos">
<%do while not rscat.EOF%>
<li><%= rscat("categoria")%></li>
<% rscat.MoveNext
if rscat.EOF then Exit do %>
<% Loop %>
</ul>
</dd>
<dt>INFORMATIVO</dt>
<dt class="no_border">CONTATO</dt>
</dl>
</div>
jquery:
<script type="text/javascript">
$(document).ready(function(){
$('dd').hide();
$('dt a.submenu').click(function(){
$("dd:visible").slideUp("slow");
$(this).parent().next().slideDown("slow");
return false;
});
});
</script>
i'm trying too, use this https://stackoverflow.com/questions/10681033/accordion-menu-active-state-after-link-click but dont work...
what i try (but don't work):
<script type="text/javascript">
$(document).ready(function(){
$('dd').hide();
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
$("dt a.submenu[href='" + sPage + "']").parents("dd:visible").show();
$('dt a.submenu').click(function(){
$("dd:visible").slideUp("slow");
var checkElement = $(this).next();
if ((checkElement.is("dd")) && (checkElement.is(":visible"))) {
return false;
}
if ((checkElement.is("dd")) && (!checkElement.is(':visible'))) {
$(this).parent().next().slideDown("slow");
checkElement.slideDown("normal");
return false;
}
});
});
</script>
Well, the first sublinks ul point to especific pages, but the another sublink ul class=produtos show the categories that's on database, and uses same link on each categories like: produtos_categoria.asp?categoria=xxxxxx...
If the user, click on "EMPRESA", on the page empresa.asp the QUEM SOMOS menu need to be opened. And if the user click on some categories under the menu PRODUTOS, on the page produtos_caegoria.asp the PRODUTOS need to be opened..
I'm clear?
So.. what i need to do?
FIDDLE: http://jsfiddle.net/Qf7Js/1/
check this jsfiddle to see if it does what you require. As far as I could understand the problem, you want to, on page load, automatically open the accordion menu that contains the current link.
This can be achieved with following code
//say this is the current link which can be retrieved in real website using window.location object
var init_link = 'institucional.asp'
//then instead of hiding all <dd>, using $('dd').hide(), you only hide the ones that don't contain an <a> that has href equal to init_link.
$('dd').filter(function () {
return $('a[href="' + init_link + '"]', $(this)).length == 0
}).hide();
Just change the init_link value to what the current URL. Watch out for the hostname part because your <a> might not contain absolute URL. This might help Get current URL in web browser.
To get currnet URL without the hostname part, you could (not must) use following code
var init_link = window.location.href.replace(window.location.protocol+'//'+window.location.hostname+'/', '')
To clarify, it seems like all you are looking to do is apply a class to the dt in addition to hiding/showing the next dd item? This can be achieved with callback functions, or by simply chaining the method on. Something like this:
<script type="text/javascript">
$(document).ready(function(){
var $menu = $('dl.menu');
$('dd', $menu).hide();
$('dt a.submenu', $menu).on("click", function(e){
e.preventDefault();
var $parent = $(this).parent('dt');
if($parent.hasClass('active')){
$parent.removeClass('active').next('dd').slideUp("slow");
} else {
$parent.siblings('.active').removeClass('active').siblings("dd").slideUp("slow", function(){
$parent.addClass('active').next('dd').slideDown("slow");
});
}
$("dd:visible", $menu).slideUp("slow", function(){
$(this).removeClass('active');
});
$(this).parent().next().slideDown("slow");
});
});
</script>
Hope this helps provide some direction.
I have a task to highlight the menu as selected while loading the page. For that I have the following code:
$('.menuHeader').each(function () {
$(this).attr('id', 'menu' + ($(this).index() + 1));
$(this).val($(this).index() + 1);
// Set the dynamic ids for links
$(this).find('a').attr('id', 'link' + ($(this).index() + 1));
//alert('New ID : ' + $(this).find('a').attr('id'));
});
$('.menuHeader a').click(function () {
alert("a");
$('.menuHeader a').removeClass('menuHeaderActive');
$(this).parent().parent(".menuHeader").addClass('menuHeaderActive');
});
But when I select the second menu, it's refreshed and missing the selection.
HTML:
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
How can I solve this problem?
function Home() {
window.location.href = "../../home/welcome";
}
function NewTransaction() {
window.location.href = "../../EnergyCatagory/index";
}
I think you could amend your hyperlinks to include the correct url. Then in you jQuery test the browsers current url against the hyperlinks url - if it's a match apply your menuHeaderActive class.
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('.menuHeader a[href="' + currentUrl + '"]');
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
When the page reloads after one of the menu links have been clicked the script I've shown should run and $('.menuHeader a[href="' + currentUrl + '"]'); should find the menu link (hyperlink/a-tag) that matches the url the user navigated too. Then it's a case of finding the container div and adding your class.
Basically you don't add the css class when the user clicks the menu link; you have to set the css class after the page has redirected to the other page. So it's the other page that has to set the css class against the correct active menu link. There are 100's of ways to do this but based on what you've provided matching urls is the simplest.
Personally I'd have each page register a page id that corresponds to one of the menu links. Something like this...
HTML
Note the attribute data-associated-page-id added to each menuHeader div
<div class="menuBar">
<div class="menuHeader ui-corner-top" data-associated-page-id="home-welcome">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top" data-associated-page-id="energy-catagory-index">
<span>New Transaction</span>
</div>
</div>
Javascript
Added to each page
document ready handler for welcome page aka ../../home/welcome
$(document).ready(function () {
SetActiveMenuCssClass('home-welcome');
});
document ready handler for energy catagory index page aka ../../EnergyCatagory/index
$(document).ready(function () {
SetActiveMenuCssClass('energy-catagory-index');
});
function defined globally
function SetActiveMenuCssClass(pageId) {
// finds div with menuHeader class that has the attribute data-associated-page-id equal to the page id
// then sets the active class
$('.menuHeader[data-associated-page-id="' + pageId + '"]')
.addClass('menuHeaderActive');
}
If you were using a server side language like PHP then you could do something like this https://stackoverflow.com/a/11814284/81053
NOTE: The answer Chris provided works really well, but you have to actually have the link in the href of <a></a>, otherwise it will be undefined.
You could add an id to a with the link and then use
var menuLink = $('#'+currentUrl);
the code provided by Chris
(this way the page won't redirect because you clicked the link but will run the function instead)
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
And the JS
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('#'+currentUrl);
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
On a side note, if that's a different page you only have to add menuHeaderActive to the active a and remove it from the other on that specific page
I have a standard css/jquery menu where I use addClass/removeClass to set whatever li I am on to 'current'. However, the code to do this uses $(this). I want to also do this same set of procedures from links not in the menu. For example, I would like the menu 'active' flag to be in the right place after following a page link that is somewhere buried in the page content and not in the menu itself.
Menu HTML
<ul class="nav2">
<li class="current">Page one</li>
<li>Page two</li>
<li>Page three</li>
<li>Page four</li>
</ul>
Page HTML
<p>Herein you will find a further description of
page two.
Javascript
$('a[rel=panel]').click(function (e) {
$('a[rel=panel]').parent('li').removeClass('current');
$(this).parent().addClass('current');
//$("a [href='" + $(this).attr('href') + "']").parent('li').addClass('current');
});
(The commented out line is my failed attempt to make the "secondary" link act just like the "primary" link in the menu.)
Help? Thanks!
This should work:
$('a[rel=panel]').click
(
function (e)
{
$('.current').removeClass ('current');
var Targ = $(e.target).attr ('href');
if (Targ)
$("ul.nav2 a[href*='" + Targ + "']").parent ().addClass ('current');
}
);
.
See it in action at jsbin.
As the link (a element) inside the content has no list item (li) element as parent (it is p and you don't show further ancestors), it should just be:
$("a [href='" + $(this).attr('href') + "']").addClass('current');
But that assumes that you defined you CSS accordingly and the class current has effects when attached to a link element.
$('a[rel=panel]').click(function (e) {
$('a[rel=panel]').parent('li').removeClass('current');
// $(this).parent("li").addClass('current');
$(".nav2 a[href='" + $(this).attr('href') + "']").parent('li').addClass('current');
});
this worked fine over at:
http://jsfiddle.net/s2vxe/
let me know if you need more in this one.
Thanks for the help, I see what you guys are doing, but it isn't working for what I need.
# Felix: I need to set 'current' class for the parent (li) not for (a). Also this is all just 1 page. I am using jquery scrollTo to slide things around onClicks.
# Brock: Your example works perfectly, however:
I am trying to use this in conjunction with jquery lavalamp, and even though the 'current' class gets correctly applied to the right (li) I still cannot get the visual current indicator to stick to the right menu item.
More fully, my code in (head) is:
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.min.js"></script>
<script type="text/javascript" src="js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="js/jquery.scrollTo-1.4.2-min.js"></script>
<script type="text/javascript" src="js/scrollto.js"></script>
<script type="text/javascript">
$(function() {
$(".nav2").lavaLamp({fx: "backout", speed: 500, click: function(event, menuItem) {
return true;
} }); });
</script>
where scrollto.js contains
$(document).ready(function() {
//Get the height of the first item
$('#mask').css({'height':$('#tab-1').height()});
//Calculate the total width - sum of all sub-panels width
//Width is generated according to the width of #mask * total of sub-panels
$('#panel').width(parseInt($('#mask').width() * $('#panel div.tab').length));
//Set the sub-panel width according to the #mask width (width of #mask and sub-panel must be same)
$('#panel div.tab').width($('#mask').width());
//Get all the links with rel as panel
$('a[rel=panel]').click(function (e) {
//Get the height of the sub-panel
var panelheight = $($(this).attr('href')).height();
//Resize the height
$('#mask').animate({'height':panelheight},{queue:false, duration:500});
//Scroll to the correct panel, the panel id is grabbed from the href attribute of the anchor
$('#mask').scrollTo($(this).attr('href'), 800);
//Set class for the selected item
//.parent() added for toggling li classes instead of a classes
//$('a[rel=panel]').parent('li').removeClass('current');
$('.current').removeClass ('current');
//$(this).parent().addClass('current');
var Targ = $(e.target).attr ('href');
if (Targ) {
$("ul.nav2 a[href*='" + Targ + "']").parent ().addClass ('current');
}
//Discard the link default behavior
//return false;
e.preventDefault();
});
$('#mask').scrollTo('#tab-1', 400 );
});
Thanks for any further help!