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
Related
I have a page shows a list of rows and with a pagination, when you click on next page the next page loads in same page contains another list of rows. so basically next page loads a bunch of other rows without my exact page been reloaded
So the problem im haven is i use this script below while it works fine but when the next page loads in same window this script does not work for them.
I hope i make sense here :) what is a good solution for this?
$('.ltwitch').each(function () {
var tnick = $(this).data('tnick');
var span = $(this).next();
$.getJSON("https://api.twitch.tv/kraken/streams/" + tnick + ".json?callback=?", function (data) {
if (data.stream === null) {
span.html(
'<strong class="ipsOnlineStatus ipsOnlineStatus_offline"><i class="fa fa-circle"></i></strong><h4 class="ipsDataItem_title ipsType_break"> ' + tnick + ' </h4><div class="ipsDataItem_meta">Offline</div>');
} else {
var views = data.stream.viewers;
var game = data.stream.game;
span.html(
'<strong class="ipsOnlineStatus ipsOnlineStatus_online"><i class="fa fa-circle"></i></strong><h4 class="ipsDataItem_title ipsType_break"> ' + tnick + ' </h4><div class="ipsDataItem_meta"> ' + views + ' viewers </div><div class="ipsDataItem_meta">Playing: '+ game +' </div>');
}
$(function() {
var online = $('.ipsOnlineStatus_online').closest('.cCmsRecord_row');
var first = $('.cCmsRecord_row')[0];
online.each(function() {
$(first).before(this);
});
});
short of HTML
<ol class="List">
<li class="row">
<div class="main">
<a href="#" class="ease">
<div class="ltwitch" data-tnick="esl_lol"></div>
</a>
</div>
</li>
<li class="row">
<div class="main">
<a href="#" class="ease">
<div class="ltwitch" data-tnick="esl_lol"></div>
</a>
</div>
</li>
....
....
....
</ol>
<div data-role="tablePagination">
<ul class="ipsPagination">
<li class="ipsPagination_prev ipsPagination_inactive">Prev</li>
<li class="ipsPagination_next">Next</li>
</ul>
</div>
It sounds like you want to wrap your work in a named function so you can call it on subsequent paging. Your code right now is most likely in a document ready which is only called on initial page load. Turning all of that work into a function now allows it to be called many times.
function myFunction () {
...
};
myFunction();
Then where your pagination code is set up ( I figure an anchor click binding ) just call myFunction() again.
$('.ipsPagination_next').click(function(){
...
myFunction();
});
I would note that if these two areas are in different document ready functions or different files, ideas like scope and encapsulation might become problematic. We'd have to see more code to confirm if it would be an issue. If you are having problems you could put the function myFunction() onto the root which would be outside of any document ready, load, or whatever you might be using. Then it would be on the root or window level.
window.myFunction = function () {
...each(... your current work
};
This could be used if you aren't sure about encapsulation or how scope works.
Your $('.ltwitch') selector only captures the classes present in the first page. When a subsequent page is loaded, $('.ltwitch') is not executed again on the new classes.
I suggest that you somehow differentiate between classes corresponding to already loaded pages, and classes corresponding to new pages. You could do this by adding a class, e.g. .already-loaded to the classes as you load them.
$.getJSON("https://api.twitch.tv/kraken/streams/" + tnick + ".json?callback=?", function (data) {
$(this).addClass('already-loaded'); // Mark as loaded.
...
This way, replace your first line with this:
$('.ltwitch').not('.already-loaded').each(function () {
...
Not tested, but could work.
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 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>
i have this HTML Code:
<div class="tab-box">
Tab1
Tab2
Tab3
Tab4
</div>
this lists the tabs...
then each tab is like:
<div class="tabcontent" id="tab1-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab2-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab3-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab4-1">
tab1 content
</div>
then the jquery code:
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
localStorage.selectedTab = $(this).index() + 1;
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
// search for local storage
if (localStorage.selectedTab) {
$(".tabLink:eq(" + (localStorage.selectedTab - 1) + ")").click();
}
});
the jquery above, i have tried to make it so it remembers the last tab selected if the page is refreshed. however, this only works with one page. if i change to view a different page with tabs, it selects a random tab as i cannot find the last one selected because it was on a different page with a different name.
how can i make it remember the last selected tab for each page?
What about cookies?
document.cookie = "tabId=" + tabeId;
then check it:
tabId = document.cookie
You can use a cookie such as document.cookie = selectedTab ,
or you can send the value of the selected tab back to the page via an ajax request such as:
var jqxhr = $.get( "example_page.php", {selectedTab: "3"} );
First, this is really bad. You are just repeating yourself.
$(".tabLink").each(function(){
$(this).click(function(){
Just use this
$(".tabLink").on("click", function() {
The rest of the method, just store the ID of the element.
// Stop the href from functioning
e.preventDefault();
// Store the tab identity in localStorage
localStorage.selectedTab = $(this).attr("id");
// Toggle the links
$(this).addClass("activeLink").siblings().removeClass("activeLink");
// Toggle the tabs
$(".tabContent").hide();
$("#" + localStorage.selectedTab + "-1").show();
});
and to show the selected tab on load
if ($(localStorage.selectedTab).length === 1) {
$(localStorage.selectedTab).click();
} else {
$("#tab1").click();
}
Try this out with my fiddle: http://jsfiddle.net/itanex/5sf8p/
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.