.addClass not working (gets removed on refresh) - javascript

I'm pretty new to jQuery and I'm trying to set a class based on localStorage.getItembut it isn't working. Here is my code:
if (localStorage.getItem("active_layout") == 2) {
$("#laa").addClass("active");
};
The localstorage item has the value of 2 and the class gets added when I click on the element. But when I refresh, it gets removed. Is it possible to keep it there and not get removed on refresh?

Try re-adding the class on document ready:
$(function() {
if (localStorage.getItem("active_layout") == 2) {
$("#laa").addClass("active");
};
});

add Active Class as default and remove it when you not need ...
if (localStorage.getItem("active_layout") !== 2) {
$("#laa").removeClass("active");
};
or add this Class Ready method
$(document).ready(function(){
if (localStorage.getItem("active_layout") == 2) {
$("#laa").addClass("active");
};
});

When the page is refreshed you will get a completely new page. Changes done with javascript will have to be redone.
If you want to use localstorage you will have to re-add the class on every refresh (Like Evan's answer).
You could also add some serverside logic so that the html is served with the class you want. However the server cannot read localstorage - you could use a cookie.

Related

JQuery JavaScript, reload page before changePage, doesn't work as expected

I'm trying to force an update of my jQuery page before I want to change the page.
Code looks like this:
function popupOrRedirect2() {
location.reload();
var content = document.getElementById('invisibleDiv').innerHTML;
if (content > 0) {
$.mobile.changePage("http://localhost:8080/application/test");
} else {
$("#popupDialog4").popup("open");
}
}
I need to read a value from a hidden div, but the div gets updated only after the page is getting reloaded. I must ensure to have the latest value.
The problem is, it doesn't work. If I remove the location.reload() it works... but it doesn't have the newest value.
Any hint on how to achieve the behavior that I want?
I'm using jQuery mobile 1.8.3.
A quick and dirty way might be to use URL params to determine whether to reload.
Instead of:
location.reload()
you could do:
if (location.search !== '?reloaded=1') {
location.search = "reloaded=1"; //triggers a reload once
}

How to have 1 jQuery file with functions used on different pages?

So I am trying to keep all my functions in 1 jQuery file. Still learning jQuery btw
However I'm running into problems where a div id doesn't exist on a different page and it throws and error. I use the Pop Easy modal plugin. I call $('.modalLink').modal() to initialize the plugin. It works on my home page, but will raise error on my FAQ page because there is no div with modalLink class.
I don't want to create separate files, so how would you re-write this?
$(document).ready(function () {
// PopEasy on Home Page
$('.modalLink').modal({
trigger: '.modalLink', // id or class of link or button to trigger modal
olay:'div.overlay', // id or class of overlay
modals:'div.modal', // id or class of modal
animationEffect: 'fadeIn', // overlay effect | slideDown or fadeIn |
videoClass:'video', // class of video element(s)
close:'.closeBtn' // id or class of close button
});
/*... other code for other pages go below ....*/
// Register Page
$('.login-window input').on('click focusin', function() {
this.value = '';
});
// FAQ Page
// FAQ sidebar menu
$('#faq-btn-general').click(function() {
$(this).parent().addClass('faq-blue');
$('#img-general-on').show();
$('#img-general-off').hide();
$('#dl-general').fadeToggle("slow", "linear");
});
});
If there is no method .modal(), then that is probably because you don't have the proper library loaded to support the .modal() method.
For a well behaved jQuery method (which I assume .modal() is), there should be no problem with:
$('.modalLink').modal();
if the .modalLink object doesn't exist. The $('.modalLink') jQuery object will be empty and calling .modal() on it will just do nothing (or that's how jQuery methods are supposed to be written anyway). If the .modal() method is not well behaved, then you can protect it yourself with this:
// makes sure the .modalLink object exists and that the `.modal()` method exists
var modalObj = $('.modalLink');
if (modalObj.length && modalObj.modal) {
modalObj.modal(...);
}
I would recommend checking to see if the objects exist before adding events to them
You can do so with this.
if ( $('#myDiv').length ){}
So to replace some of your code it would look like this
if ( $('.login-window input').length ){
$('.login-window input').on('click focusin', function() {
this.value = '';
});
}
You can test is method exists such as
if ($.fn.modal) {
$('.modalLink').modal({
trigger: '.modalLink', // id or class of link or button to trigger modal
olay:'div.overlay', // id or class of overlay
modals:'div.modal', // id or class of modal
animationEffect: 'fadeIn', // overlay effect | slideDown or fadeIn |
videoClass:'video', // class of video element(s)
close:'.closeBtn' // id or class of close button
});
}
But that can be long.... You can also add an ident class on the body that you check in the javascript file.
if ($('body').hasClass('forum-section')) {
// Include code concerning that section only
}
Hope that helped
try something like:
if ( $('.myClass').length > 0){
$('.myClass').modal(....)
}

Javascript display html if div exists

I am trying to display a table (or ul) that will contain a navigation bar on my page, but only displays the tabs that will contain jquery called divs present on the html.
Essentially, it's a single html document that contains all divs, jquery hides all divs but the first, and the nav bar will allow to navigate through each.
Now I am trying to make it easy to use for my client, so that the menu items will only exist if the div for it also exists. I've got most of it done, the only thing is actually knowing if a div exists.
I tried using this:
if(document.getElementById("page1")) {
document.write("<b>Good morning</b>");}
else
{
document.write("<b>Bad morning </b>");
}
When I place the above code within the div page1, it returns true. Is there no way to do it from the top of the page and not within the div?
Thanks!
Update:
As suggested by many, I have used the following:
$j(document).ready(function(){
//Hide the sections we don't need right away
$j("#page2").hide();
$j("#page3").hide();
$j("#page4").hide();
if ($j('#page1').length > 0) {
var page = 'Excellent Morning' ;
}
});
Then when I try to use:
document.write(page);
It displays the following instead:
[object HTMLBodyElement]
Why not use jQuery since you are already?
if ($('#page1').length > 0) {
// do stuff...
}
EDIT: As davin pointed out, your code should be evaluated after the DOM has been rendered. You can do this by placing it in a $(document).ready call:
$(document.ready(function() {
if ($('#page1').length > 0) {
// do stuff...
}
});
EDIT 2: Based on the OP's edits, a better solution would be to add a placeholder element and to set its content (like FishBasketGordo suggested). An example of this:
$(document.ready(function() {
//Hide the sections we don't need right away
$("#page2, #page3, #page4").hide();
if ($('#page1').length) {
$('#myPlaceHolder').html('<b>Good Morning</b>');
}
else
{
$('#myPlaceHolder').html('<b>Bad Morning</b>');
}
});
Somewhere else in the document...
<span id="myPlaceHolder"></span>
If you place it at the top of the page, the page1 div doesn't exist when the code runs. If you are using jQuery, place the code in a $(document).ready event. Then, you can put it where you want it within the markup. Here's an example:
$(document).ready(function() {
if (document.getElementById("page1")) {
document.write("<b>Good morning</b>");
} else {
document.write("<b>Bad morning </b>");
}
});
Although, rather than doing a document.write, I would consider having a placeholder span or div, and setting it's innerHTML property (or use jQuery's html method). I would also use CSS for my style instead of <b> tags, but that's another matter entirely.
You can use
if ($(selector).length > 0) {
// element exists
}
or you can check out this post for a more elegant solution
Is there an "exists" function for jQuery?

js: hiding divs

I am pretty new to Javascript so please bear with me.
$('#bioContent').css('display','none');
$('#skillsContent').css('display','none');
$('#credsTab').css('background-color','#fff');
$('#credsTab a').css('color','#19d700');
$('#bioTab').css('background-color','#ccc');
$('#bioTab a').css('color','#444');
$('#skillsTab').css('background-color','#ccc');
$('#skillsTab a').css('color','#444');
$('#credsTab').click(function(){
$('#credsContent').css('display','block');
$('#bioContent').css('display','none');
$('#skillsContent').css('display','none');
$('#credsTab').css('background-color','#fff');
$('#credsTab a').css('color','#19d700');
$('#bioTab').css('background-color','#ccc');
$('#bioTab a').css('color','#444');
$('#skillsTab').css('background-color','#ccc');
$('#skillsTab a').css('color','#444');
})
$('#bioTab').click(function(){
$('#bioContent').css('display','block');
$('#credsContent').css('display','none');
$('#skillsContent').css('display','none');
$('#bioTab').css('background-color','#fff');
$('#bioTab a').css('color','#19d700');
$('#credsTab').css('background-color','#ccc');
$('#credsTab a').css('color','#444');
$('#skillsTab').css('background-color','#ccc');
$('#skillsTab a').css('color','#444');
})
$('#skillsTab').click(function(){
$('#skillsContent').css('display','block');
$('#bioContent').css('display','none');
$('#credsContent').css('display','none');
$('#skillsTab').css('background-color','#fff');
$('#skillsTab a').css('color','#19d700');
$('#bioTab').css('background-color','#ccc');
$('#bioTab a').css('color','#444');
$('#credsTab').css('background-color','#ccc');
$('#credsTab a').css('color','#444');
})
That's my javascript implementation of tabs. Basically on click, divs hide away and others appear.
My problem with this is that on the skillsTab, there's an add skills method, and when I click on that, it refreshes the page, and when it does, it brings me back to the credsTab, the default when the page is loaded.
I was wondering if that's a way so that when it refreshes, it will stay on the skillsTab.
Keep state around, which can be done via fragment URLs or HTML5 history.
e.g., make opening up the skills tab change the fragment to #skills, which will remain across a refresh. Then check window.location.hash in your onLoad to determine what initial state your page should be in.
function switchToTab(tabName) {
// DOM/CSS manipulation etc. here
}
var tabs = ['bio', 'skills', 'creds'];
var initialTab = 'bio';
for (var i = 0; i < tabs.length; i++) {
(function(tabName) {
document.getElementById(tabName + 'Tab').addEventListener('click', function() {
switchToTab(tabName);
location.hash = '#' + tabName;
}, false);
})(tabs[i]);
}
window.addEventListener('load', function() {
if (location.hash[0] == '#')
switchToTab(location.hash.substr(1));
}, false);
window.addEventListener('hashchange', function() {
if (location.hash[0] == '#')
switchToTab(location.hash.substr(1));
else
switchToTab(initialTab);
}, false);
Untested, and there's plenty of JS libraries out there that abstract this away for you.
An initial suggestion. give all your tabs the same class, maybe class='toggleableTab' then you can use
$('.togglableTab').live('click',function(){
$('.togglableTab').not(this).hide();
$(this).show();
});
as for the page refresh. Look into using AJAX to "add" your skills live on the page without a full page refresh.
There are several tabbed solutions already in place that you could make use of - for example, http://jqueryui.com/demos/tabs/. JQuery UI is a great way to have a lot of this work done for you.
If you want to do it yourself, I would also suggest a solution using classes, but slightly different than other suggestions. Instead, have two classes, "activeTab" and "tabbable". In your css, define "activeTab" as visible, and "tabbable" as hidden. Give each tab an ID and the class of "tabbable". Have a hidden field in your form called "activeTabId". Make sure that this gets passed back from the server side when you load the page, including setting it to the default tab when you first load the page. You could then run the following code on page load to make it all play well together:
$(".tabbable").click(new function(){
$(".tabbable").removeClass("activeTab");
$(this).addClass("activeTab");
$("#activeTabId").val($(this).attr("id"));
});
$("#" + $("#activeTabId").val()).addClass("activeTab");

Javascript function to add class to a list element based on # in url

I am trying to create a javascript function to add and remove a class to a list element based on the #tag at the end of the url on a page. The page has several different states, each with a different # in the url.
I am currently using this script to change the style of a given element based on the # in the url when the user first loads the page, however if the user navigates to a different section of the page the style added on the page load stays, I would like it to change.
<script type="text/javascript">
var hash=location.hash.substring(1);
if (hash == 'strategy'){
document.getElementById('strategy_link').style.backgroundPosition ="-50px";
}
if (hash == 'branding'){
document.getElementById('branding_link').style.backgroundPosition ="-50px";
}
if (hash == 'marketing'){
document.getElementById('marketing_link').style.backgroundPosition ="-50px";
}
if (hash == 'media'){
document.getElementById('media_link').style.backgroundPosition ="-50px";
}
if (hash == 'management'){
document.getElementById('mangement_link').style.backgroundPosition ="-50px";
}
if (hash == ''){
document.getElementById('shop1').style.display ="block";
}
</script>
Additionally, I am using a function to change the class of the element onClick, but when a user comes to a specific # on the page directly from another page and then clicks to a different location, two elements appear active.
<script type="text/javascript">
function selectInList(obj)
{
$("#circularMenu").children("li").removeClass("highlight");
$(obj).addClass("highlight");
}
</script>
You can see this here:
http://www.perksconsulting.com/dev/capabilities.php#branding
.
Sorry for the lack of clarity. The question is how to modify the function listed first to add and remove the class: highlight, from the elements based on the hash in the url rather than onclick as it currently does.
I realize that I am modifying the style of the element inline with my current function, I would modify the class rather than the style.
Thanks.
Your problem is your first block of javascript code. If you set the element's style this will always override any class styles on the element. Currently, when you navigate to the page with a hash #strategy you modify the inline style of the element. I would suggest revising your code like this to modify the class of the element.
var hash=location.hash.substring(1);
$('#' + hash + '_link').addClass('highlight');
if (hash == ''){
$('#shop1').show()
}
Edited (Regarding your comment)
Here is what I would do:
First Create a function that adds the highlight class to a specific hash value and remove the highlight class from all others. You would probably want a default action when an invalid hash value is passed.
function highlightCircularMenuIcon(hashValue) {
if (hashValue.length) {
$('#circularMenu li').removeClass('highlight');
$('#' + hash + '_link').addClass('highlight');
} else {
//default action you did have $('#shop1').show();
}
}
Second, when the document is ready (or loaded), bind the click event for each of the LI elements in the circularMenu. Then in the click function call highlightCircularMenuIcon.
Finally in the last part of the document.ready function call highlightCircularMenuIcon with the hash string from your URI.
$(document).ready(function () {
$('#circularMenu li').click(function() {
highlightCircularMenuIcon(($(this).name).replace("_link", ""));
});
highlightCircularMenuIcon(location.hash.substring(1));
});

Categories