I have got a task to highlight the selected menu while refreshing the page. For that I want to use cookie.
Html code is
<div class="menuBar">
<div class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
Javascript file is
function Home() {
window.location.href = "../../home/welcome";
}
function NewTransaction() {
window.location.href = "../../EnergyCatagory/index";
}
But I have a code to set the menu as selected.But its not a good way.How can I pass the value of the selected menu to the page while refreshing?
this is the code for highlighting the menu
$(document).ready(function () {
var currentUrl = window.location.href;
if (currentUrl.indexOf("home/welcome") !== -1) {
$("#home").parent().parent().addClass('menuHeaderActive');
}
else if (currentUrl.indexOf("EnergyCatagory/index") !== -1) {
$("#newtransaction").parent().parent().addClass('menuHeaderActive');
}
else if (currentUrl.indexOf("portfolio/Index") !== -1) {
$("#portfolio").parent().parent().addClass('menuHeaderActive');
}
});
Give id for every menu item.
Then in the onclick() function of menu item set that id as cookie.
Set cookie
$.cookie("selectedId", $(this).attr('id'));
In document.ready function add selected class to the element with id obtained from cookie
You can implement it like this:
function goToLocation(sLocation, id) {
$.cookie("activediv", id);
window.location.href = sLocation;
}
in html:
Home
in jQuery ready:
$('#' + $.cookie("activediv")).parent().parent().addClass('menuHeaderActive');
Try to set cookises using jQuery as:
$.cookie("name", "value");
More you can read here:How do I set/unset cookie with jQuery?
Related
I am working on an AJAX pagination and I made it by using this code.
$(document).ready(function() {
var pagination = $("#pagination");
var url = urlProviderOffers;
updateContent(function(json) {});
pagination.on('click', "ul a", function(e) {
e.preventDefault();
var page_to_visit = $(this).text();
updateContent(function(json) {});
pagination.find('ul li').removeClass('active');
$(this).parent().addClass('active');
});
function updateContent(callback, page_to_visit) {
page_to_visit = typeof(page_to_visit) != 'undefined' ? page_to_visit : 1;
$.ajax({
url: url,
data: {
page: page_to_visit
}
}).done(function(json) {
if (json.total > 1) {
pagination.find("ul li:nth-child(1)").addClass('active');
}
callback(json);
});
}
url = template_url.replace(/provider_id_to_change/, providerID);
return url;
}
});
<div id="pagination">
<ul class="pagination">
<li class="active">1
</li>
<li>2
</li>
<li>3
</li>
</ul>
</div>
The problem I am having is that, any time I click on one of the links of the pagination, a function is called and inside this function I change the active link been visited by the user.
For instance, when my page is loading, the function updateContent sets the current page been visited to 1. And after clicking on another link of the pagination, I remove all the added class and add a new active class to the selected link.
In my case anytime, when a link is clicked, is set the class of the selected link to active and automatically remove the added class and set the active class to the first link.
kindly help me solve this problem
I have a fairly simple .addClass(open) function in jQuery, but am having trouble passing the right variables.
I have these two buttons in a sidebar:
<ul>
<li class="dashButton active" id="#1"><?php the_field('sidebar_text_0'); ?></li>
<li class="dashButton" id="#2"><?php the_field('sidebar_text_1'); ?></li>
</ul>
And then two divs that should open in eachother's place when it's button is clicked. mainDashWrap relates to id=#1 and editProfile relates to id=#2.
<div class="mainDashWrap dashView open">
...... content .....
</div>
<div class="editProfile dashView">
...... content .....
</div>
And my jQuery adds and removes the open class, which has display:none if there is no open class and display:block if it does have the open class.
My problem is with the //Get the attr2 part below. I don't think it's properly setting the class so that it's formatted to go into the $(newSect).slideDown() function.
$('.dashButton').click(function() {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
//Get the attr2
if ( this.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
This will add and remove the open class and hide the dashview that doesn't have the open class, but it will not add the open class to newSect or slide down newSect. How can I get attr2/newsect to set properly?
I suppose you first removed all .open in click event
$('.dashView.open').removeClass('open');
and only after that trying to slide up this elements in switchDashViews function
$('.dashView.open').slideUp('2000'...
But .open are already deleted
Upd. try not to use var keywords in this block
if ( this.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
because attr2 can be out of scope. Just
if ( this.id == '#1') {
attr2 = '.mainDashWrap';
}
else { attr2 = '.editProfile' }
Remove # from your id in your HTML, it is not a allowed character in id, (Imagine what selector will look like $(##1), pretty bad, huh?).
Add a data-attribute so that you can get rid of if() .. else() ...
HTML
<ul>
<li class="dashButton active" data-class=".mainDashWrap" id="1"><?php the_field('sidebar_text_0'); ?></li>
<li class="dashButton" data-class=".editProfile" id="2"><?php the_field('sidebar_text_1'); ?></li>
</ul>
jQuery
$('.dashButton').click(function() {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
// Do this
var attr2 = $(this).data("class");
/* Or you can do this
if ( this.id == '1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
*/
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
Make sense?
Don't include # in the ID. While it's legal in modern browsers, it's confusing and will make it difficult to access the element using jQuery or CSS selectors. Instead use
<li class="dashButton active" id="1">
Then change the if to match this:
if (this.id = "1")
I also suggest you use more meaningful IDs than just numbers.
this can be different depending on the function scope, try to use event.target instead so this.id would be event.target.id.
See your example of your code with changes:
$('.dashButton').click(function(event) {
//Switch active Tab Buttons and close the Menu.
$('.dashButton.active').removeClass('active');
$(this).addClass('active');
$('.dashView.open').removeClass('open');
//Get the attr2
if ( event.target.id == '#1') {
var attr2 = '.mainDashWrap';
}
else { var attr2 = '.editProfile' }
switchDashViews(attr2);
});
function switchDashViews(newSect) {
//close active section
$('.dashView.open').slideUp('2000', function() {
$('.dashView.open').removeClass('open');
$(newSect).slideDown('2000', function() {
$(newSect).addClass('open');
});
});
};
I think this.id won't work. ~~You want to convert this to a jQuery object via $(this) then use the attr() method to retrieve the 'id'. So something like...~~
EDIT
Turns out this.id does work! Didn't notice the id="#1" you had in your HTML tags. Yep, as others have pointed out, that'll be the culprit.
I am trying to add an active class to nav item, depending what page your on. I am using this script:
<script type="text/javascript">
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(id).siblings().find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$(selectedolditem).siblings().find(".active").removeClass("active");
$(selectedolditem).addClass("active");
}
});
</script>
See full jsfiddle here: https://jsfiddle.net/ebo7hLo9/
It adds the active class, but it loads a new page, it disappears. What am I doing wrong?
https://jsfiddle.net/ebo7hLo9/10/ - here's a fiddle!
$(document).ready(function () {
$("#side-bar a").click(function () {
var id = $(this);
$(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", $(id).text());
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem !== null) {
$("a:contains('" + selectedolditem + "')").addClass("active");
}
});
Your code was having issues remembering what element to grab. I think it's due to the web storage API's unfamiliarity with objects. Instead I got the text from the element that was selected, stored it in localStorage and on page load matched it with the correct element. Also there was part of your code that was dealing with finding the class "active" within the siblings() of the selected element and removing it. That complex of code is largely unnecessary. I replaced it with the class selector $(".active")
I didn't change this in the code, but I'd advise against using localStorage in favor of sessionStorage so that the storage will clear itself on tab/browser close.
For more info take a look at this previous stackoverflow post: Storing Objects in HTML5 localStorage
Here is a possible solution: https://jsfiddle.net/6yyLpma1/
$("#side-bar a").click(function () {
var id = $(this);
$('#side-bar').find(".active").removeClass("active");
$(id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
Instead of $(id).siblings() use $('#side-bar'). Use the same logic in other location.
Using data elements and a delegate function: https://jsfiddle.net/ebo7hLo9/12/
HTML
<span id="delegateAnchor">
<div id="side-bar">
<ul>
<li>Home</li>
<li>Who we are</li>
<li>Services</li>
<li>What to expect</li>
<li>Representative clients</li>
<li>Success stories</li>
<li>Current litigation</li>
<li>What if you could not be a doctor?</li>
</ul>
</div>
</span>
Javascript
$(document).ready(function () {
$('#delegateAnchor').on('click', '#side-bar a', function() {
var $this = $(this);
var linkId = $this.data('desc');
$this.closest('ul').find('a').removeClass("active");
$this.addClass("active");
localStorage.setItem("menuSelection", linkId);
});
var selectedLinkId = localStorage.getItem("menuSelection");
if (selectedLinkId !== null) {
$('#side-bar a[data-desc="'+ selectedLinkId +'"]').trigger("click");
}
});
I have this link:
<div name="top">
<!-- some code -->
<a class="myLinkToTop" href="#bot">Click</a>
<!-- some code -->
<div name="bot">
I wish to change the href attribute when it's clicked. I'm using this script:
<script>
$(".myLinkToTop").click(function(){
$("a.myLinkToTop").attr("href","#top");
});
</script>
But I have 2 problems:
When I click the link its href changes, but the action sends me to the #top, instead of #bot.
After that, I want the href to switch between #top and #bot. I don't know how to do that so I was thinking about changing my class value with "toggleclass()" but I don't think this is the best use for my problem.
This will move to the current href on link and then change it:
$(".myLinkToTop").click(function(e){
e.preventDefault();
window.location.href = this.href;
this.href = this.hash === "#top" ? "#bot" : "#top";
});
Like Banana said, you could use an if/else statement to check the current href value. If the current value is #bot, set it to #top after 1 second (that will allow the original value to go through first). And vice versa if the current value is #top.
$(".myLinkToTop").on("click", function () {
var $this = $(this), // cache "this as a jQuery object"
href = $this.attr("href");
if (href === "#bot") {
setTimeout(function () {
$this.attr("href", "#top");
}, 100);
} else {
setTimeout(function () {
$this.attr("href", "#bot");
}, 100);
}
});
I am trying to toggle an image when a class is clicked. So far I have this (below) and it works to change my 'plus.png' to my 'minus.png' but I need it to change back to my 'plus.png' if the class is clicked again.
I have the following jQuery:
<script type="text/javascript">
$(document).ready(function () {
$('label.tree-toggler, .yellow').click(function () {
$(this).parent().children('.yellow').attr('src', 'img/minus.png');
});
});
</script>
HTML
<li><label class="tree-toggler nav-header">Saftey and Emissions</label><img class="yellow" src="img/plus.png"><hr></hr>
<ul class="nav nav-list tree">
<li>link<img class="yellow" src="img/chevron-right.png"><hr></hr></li>
<li>link<img class="yellow" src="img/chevron-right.png"><hr></hr></li>
</ul>
</li>
Is someone could help me out by adding to what I have, it would greatly be appreciated!
You can add/remove a class to keep track of which image src you are using. Something like this:
$('label.tree-toggler, .yellow').click(function () {
if ( $(this).parent().children('.yellow').hasClass('minus') ) {
$(this).parent().children('.yellow').attr('src', 'img/plus.png').removeClass('minus');
} else {
$(this).parent().children('.yellow').attr('src', 'img/minus.png').addClass('minus');
}
});
You could also use a data attribute and do something similar:
$('label.tree-toggler, .yellow').click(function () {
if ( $(this).parent().children('.yellow').data('current_src') == 'minus') {
$(this).parent().children('.yellow').attr('src', 'img/plus.png').data('current_src', 'plus');
} else {
$(this).parent().children('.yellow').attr('src', 'img/minus.png').data('current_src', 'minus');
}
});
Using the data attribute would require initially setting data-current_src='minus' on the element.
the way i will do it is...
$(document).ready(
function() {
$(".className").click(
var imgPath = $("img").attr('src');
if(imgPath === "+.png") { // check against current path
// change the path to -
} else {
// change the path to +
}
); } );
i didn't test it, but that's the idea
I would recommend adding another class like .active or .shown through JQuery when you switch the image around. That way you could check the current state of the object you're querying.
The Jquery would probably look something like
$('label.tree-toggler, .yellow').click(function () {
// If the active class is NOT applied
if( !( $(this).parent().children('.yellow').hasClass('active') ) ) {
// Apply it and change the image
$(this).parent().children('.yellow').addClass('active').attr('src','img/minus.png');
}
else
$(this).parent().children('.yellow').removeClass('active').attr('src', 'img/plus.png');
});
What's happening here is the active class is being used to determine the state of the image displayed. When you click it, you'll change the image and apply the flag.
After every click the flag is checked and behaves accordingly. Hope that helps! I'm still new to S.O. =.="
If you want to do it in JS, I suggest you to put :
your initial image in src
your alternative image in data-alternative
Like this :
<li>
<label class="tree-toggler nav-header">Saftey and Emissions</label>
<img class="yellow" src="img/plus.png" data-alternative="img/minus.png"><hr></hr>
<ul class="nav nav-list tree">
<li>link<img class="yellow" src="img/chevron-right.png"><hr></hr></li>
<li>link<img class="yellow" src="img/chevron-right.png"><hr></hr></li>
</ul>
</li>
And the JS :
<script type="text/javascript">
$(document).ready(function () {
$('label.tree-toggler, .yellow').click(function () {
var yellow = $(this).parent().children('.yellow').first();
var alternative = yellow.data('alternative');
yellow.data('alternative', yellow.attr('src'))
.attr('src', alternative );
});
});
</script>
Did you see the toggle function of Jquery?
http://api.jquery.com/toggle/