js: hiding divs - javascript

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");

Related

jQuery history usage

I have created a webpage that uses jQuery to show and hide elements. The obvious problem now arose; the back and forward browser buttons don't work anymore as everything is loaded within a single location.
I know the answer lies within jQuery History but after busting my head for several hours on their website and examples given here on stackoverflow, I still cant manage to:
A) create a history entry (I think i got this covered but not 100% sure)
B) animate the page transition with my own function (displayed beneath)
This is the website: www.grommit.nl
There are 4 sub-pages that require a history entry when called upon.
This code shows the transition of the "wordpress page". The other pages work in a similiar way. (so far I have only managed to generalize the last part of the pageload with the "LoadPageContent" function, the bit before that is different with every page)
var LoadPageContent = function() {
$(".sceneBody").slideDown(function() {
$(".aftertitle").css('width', '4em');
$(".mediacontainer").fadeTo('0.3s', 1,)
});
$("#goWordpress").click(function () {
$("#homeScene").fadeOut(function () {
$("#wordpressMessage").fadeIn(function() {
$(this).delay(300).slideUp(function() {
$("#wordpressPage, #grommitFixed").slideDown(function() {
LoadPageContent();
});
});
});
});
});
this is the function that is currently working as a previous button within the DOM. I would like this function to execute when the previous button is clicked.
var goBack = function() {
$(".aftertitle").css('width', '0em')
$(".mediacontainer").fadeTo('0.3s', 0, function() {
$(".scenebody, #grommitFixed").slideUp(function() {
$("*[id*=Page]:visible").each(function() {
$(this).slideUp(function() {
$("#homeScene").fadeIn();
});
});
});
});
};
In html5 you have something called pushstate, that you can use to tell the browser what to go back to. Check out:
html pushstate

Remembering jquery toggle across site?

I want to be able to hide and unhide a lengthy menu with a button click, and that I have been able to do. But I don't want visitors to have to hide the menu every time they visit a new page, so I would like their last click to be remembered. This I have not been able to do. Any help is appreciated. I am even open to a better way to do this.
The code I thought would work, but doesn't, is:
$(document).ready(function(){
$("button").click(function(){
$("div.themenu").toggle(100);
});
});
$(function(){
if($.cookie){
$("#themenu").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
}
$('#menubutton').on('click', function(){
$("#themenu").toggle();
$.cookie("toggle-state", $("#themenu").is(':visible'), {expires: 1, path:'/'});
});
});
The code for the button they click is:
<button id="menubutton" class="myButton">Show / Hide Menu</button>
And the long, long menu is shown like this:
<div class="themenu">Long Long Menu Code</div>
Just for fun: here's an alternative solution which doesn't require a cookie, but sets a URL parameter:
//on page load
if (location.href.match('menu=show'))
$("#themenu").toggle();
//for every link click, block & redirect with menu=show if menu is visible
$(document.body).on('mousedown', 'a', function(e) {
e.preventDefault();
var menuParam = (location.href.match('?') ? '&' : '?') + 'menu=show';
location.href = $("#themenu").is(':visible') ? this.href + menuParam: this.href;
});
localStorage is a good place to store this kind of state. Setting is as easy as localStorage.menu = 'hidden' or localStorage.menu = 'visible', checking can be done with (localStorage && localStorage.menu==='hidden'). People with REALLY old browsers won't get the feature but that's a very small slice of users. This setting will live across visits to the site but only in the same browser. There is an issue with some browsers in 'private browsing' mode. They sometimes make localStorage cause an error when modified.

Can I use multiple intro.js with more than 2 pages?

I want to use intro.js with more than two pages.
Is it a simple way to do it?
Yes, you can. If you look at code for intro.js example with multiple pages https://github.com/usablica/intro.js/tree/master/example/multi-page you can see that first page has code that redirects to second page after user click the button:
<script type="text/javascript">
document.getElementById('startButton').onclick = function() {
introJs().setOption('doneLabel', 'Next page').start().oncomplete(function() {
window.location.href = 'second.html?multipage=true';
});
};
</script>
And on the second page we use regex to check if user is going through intro. You will need to add code like that to each page, with url address to the page that should be shown next.
If you want to have more than one "intro flows" (since the question title said multiple), you can give them names or numbers. Then, instead of adding multipage=true you can use multipage=beta_version or multipage=1 and use reqex to check if user should see intro, and if yes, which one.
<script type="text/javascript">
if (RegExp('multipage', 'gi').test(window.location.search)) {
document.getElementById('startButton').onclick = function() {
introJs().setOption('doneLabel', 'Next page')
.start().oncomplete(function() {
if (RegExp('multipage=2', 'gi').test(window.location.search)) {
window.location.href = 'third.html?multipage=2';
}
else {
window.location.href = 'unicorn.html?multipage=3';
}
});
};
}
</script>
That might be not the nicest code ever :), but ( like Rich said ) without more information I can only guess this is what you want to do? But hopefully, it will give a general idea.
if (RegExp('multipage', 'gi').test(window.location.search)) {
introJs().setOption('doneLabel', 'Next Page →').start().oncomplete(function() {
window.location.href = 'nextpage?multipage=true';
});
}
I was able to use intro.js for a complex multipage use (more complete than their official multipage example). See the issue I opened about it associated to my React solution on Codesandbox.

Google related bar - how to keep from showing up on my website

A new "google related" bar shows up at the bottom of my website. It displays links to my competitors and other things like maps, etc. It is tied in with users using the google toolbar. If anyone has any ideas on how I can disable from displaying on my web side I would sure appreciate it.
Taken from http://harrybailey.com/2011/08/hide-google-related-bar-on-your-website-with-css/
Google inserts an iframe into your html with the class .grelated-iframe
So hiding it is as simple as including the following css:
iframe.grelated-iframe {
display: none;
}
Google removed div and frame names and put everything to important so original answer no longer works on my site. We need to wait for the iframe to be created and then hide it by classname. Couldn't get .delay to work, but this does...today anyway.
$(document).ready(function() {
setTimeout(function(){
$(‘.notranslate’).hide();},1000);
});
Following javascript code tries to find the google related iframe as soon as the window finishes loading. If found, it is made hidden, else an interval of one second is initialized, which checks for the specified iframe and makes it hidden as soon as it is found on page.
$(window).load(function (){
var giframe = null;
var giframecnt = 0;
var giframetmr = -1;
giframe = $("body > iframe.notranslate")[0];
if(giframe != null)
$(giframe).css("display", "none");
else
giframetmr = setInterval(function(){
giframe = $("body > iframe.notranslate")[0];
if(giframe != null) {
clearInterval(giframetmr);
$(giframe).css("display", "none");
} else if(giframecnt >= 20)
clearInterval(giframetmr);
else
giframecnt++;
}, 1000);});
Find the parent DIV element that contains the stuff in the bar. If it has an id or name attribute, and you can control the page CSS then simply add a rule for the element, i.e. if you see something like
<div id="footer-bar-div".....
then add a CSS rule
#footer-bar-div {display:none ! important}
This will not work if the bar is inside an iframe element, but even in that case you should be able to hide it using javascript, but you will need to find the name/id of the frame, i.e.:
var badFrame = document.getElementById('badFrameId').contentWindow;
badFrame.getElementById('footer-bar-div').style.display='none';
if the frame has a name, then instead you should access it with:
var badFrame = window.frames['badFrameName']
There is also a chance that the bar is generated on-the-fly using javascript. If it is added to the end of the page you can simply add a <noscript> tag at the end of your content - this will prevent the javascript from executing. This is an old trick so it might not always work.

Using jQuery-Smooth-Scroll from one page to another?

I am currently using jQuery-Smooth-Scroll to smoothly scroll up and down to various anchor positions on one of my pages (Page 1). However, what I would also like to be able to do is, from another page (Page 2), link to Page1 (appending #bookmark to the url) and have jQuery-Smooth-Scroll pick up on the fact I am calling the page with a #bookmark and have it smoothly scroll down to the relevant position once the page has completed loading. I don't know if this is a possibility or not?
This is the version of Smooth-Scroll that I'm using:
https://github.com/kswedberg/jquery-smooth-scroll
I'm still relatively new to jQuery so I may be overlooking something obvious.
Ajma's answer should be sufficient, but for completeness:
alert(location.hash)
Edit: a more complete example:
// on document.ready {
if (location.hash != '') {
var a = $("a[name=" + location.hash.substring(1) + "]");
// note that according to w3c specs, the url hash can also refer to the id
// of an element. if so, the above statement becomes
// var a = $(location.hash);
if (a.length) {
$('html,body').animate({
scrollTop: $(a).offset().top
}, 'slow');
}
}
// }
It's possible, you want to put a call into the smooth scroll function when the page is finished loading. in jQuery, it's using $(document).ready(function () { your code } );
You'll need to put something in to parse your url to extract the #bookmark and then call the smooth scroll.

Categories