jquery scrollintoview with bootstrap scrollspy - javascript

Hello fellow stackoverflow members who use bootstrap! I appreciate your time and input. I am having trouble implementing a jQuery.scrollintoview with bootstrap scrollspy.
http://jsfiddle.net/aKK2k/1/
Above is fiddle, scrollspy is broken but the scrollintoview should still work, or am i mistaken?
Nav buttons that move the page:
<li>
<a href="#section-2" id="a-section-2">
Products
</a>
</li>
Below is the scroll-to-section
<h3 class="center" id="section-2">
So, how can Day & Night help your business today?
</h3>
Below is the JS that handles the page scrolling / hiding url / etc.
The implementation happens at
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
The whole JS
<script>
$("document").ready(function() {
$(document).on('click','.navbar li a',function(event) {
event.preventDefault();
if($.trim($(this).html())!='FAQ'){
//if($.trim($(this).html())!='FAQ' || $.trim($(this).html())!='FAQ2'){
var offset = $('#myNavbar').height()+30;
if ($(window).width() <= 768) {
var offset = 100;
}
$($(this).attr('href'))[0].scrollIntoView(250, "easeOutExpo");
scrollBy(0, -offset);
}
else
{
window.location.href = $(this).attr('href');
}
});
//document.referrer returns the url from which this page has been entered,
//we will use this to check if we are redirected from FAQs page
var previous_url = document.referrer;
if(previous_url=='http://dnwebdev.com/dev/faq/'){
//if we were redirected from FAQ page, we would have a #section-value in our url
//hash here fetched that value
var hash = document.URL.substr(document.URL.indexOf('#')+1);
//this is the important part, we are gonna trigger that the
//#section-value passed in url is _clicked_. And so the browser will
//scroll down to that section
$('.navbar li a#a-'+hash).trigger('click');
//once it scrolls down, this deletes the #section-value from url
history.pushState('', document.title, window.location.pathname);
}
});
function close_toggle() {
$('.nav a').on('click', function () {
if ($(".navbar-toggle").css("display") != "none") {
$(".navbar-toggle").click();
} else {
$('.nav a').off('click');
}
});
}
close_toggle();
$(window).resize(close_toggle);
</script>
Currently the page jumps when an "easeOutExpo" is what we are going for.
I am very new to JS, any input is appreciated.
The website is http://dnwebdev.com/
I added jqueryUI, declared jquery before ui, but the scroll still won't work.
Robert

You are invoking scrollIntoView on the raw DOM element, when you want to invoke it on the jquery matched set. Remove the [0] and try this:
$($(this).attr('href')).scrollIntoView(250, "easeOutExpo");
fiddle: http://jsfiddle.net/aKK2k/7/
(i've also added the jquery stuff to your fiddle).

Related

check if page at a certain section

I want to trigger a function when the user is on a section of the page with a specific ID (either through a link or scroll). This is what I have now but it's not working.
$(document).ready(function() {
if (window.location.pathname == '/index.html#contact') {
console.log('Viewing contact form');
}
});
UPDATE: Found what I was looking for. This is what I used:
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#contact').offset().top - 50) {
$('.modal').modal('hide');
}
});
The "- 50" is to account for my margins and paddings. When using the subtract symbol it 'assumes' your section starts higher on your page. For lower, use addition.
The "$('.modal').modal('hide');" is not needed. This is to hide a bootstrap modal when the user is on the #contact section of the page.
The window.location property in Javascript returns a location object. If you want to match a specific anchor link you need to use the hash property of the location object. Here's a list of all properties of location objects: http://www.w3schools.com/jsref/obj_location.asp.
You could check for window.location.pathname+window.location.hash
$(document).ready(function() {
if (window.location.pathname+window.location.hash == '/index.html#contact') {
console.log('Viewing contact form');
}
});
because window.location.pathname does not include the part after the hash.
Your Html code
<div id="contact">
</div>
Your Javascript code
$("#contact").scroll(function() {
/*do whatever you want*/
});

Applying .click event only to links in a certain div-container

The code already creates a navigation based on a JSON-file. The url are accessible by writing data.chapter[].subchapter[].url, the according title through data.chapter[].subchapter[].title
In case you are interested in that part or want the complete code, I uploaded it there: http://fabitosh.bplaced.net/SkriptET_iFrame_v2/
The goal now is to create a right sidebar which shows the links to the next and previous files in the structure. My approach is below.
What confuses me, is that back() is called until subchap is zero, when a link in #left is being clicked on. It should only be called when the previous-link is being clicked on. What do I have to change in order to achieve that?
Thanks a lot already!
var chap; //position in the array of the currently open chapter
var subchap; //position in the array of the currently open subchapter
function update_right() {
var path = data.chapter[chap].subchapter;
//Previous Page
if(subchap > 0) {
$("#prev").html("<b>Previous:</b><a href='"+path[subchap-1].url+"'>"+path[subchap-1].title+"</a><br/>");
$("#prev > a").click(back());
} else { //subchap == 0
$("#prev").html("");
};
}
function back() {
subchap--;
update_right();
}
$(document).ready(function() // DOM needs to exist in order to be able to add stuff in there
{
...Navigation being built up...
//------ onClick Navigation
$('#left > ul > li > a').click(
function(e)
{
chap = $(this).attr("data-chap");
subchap = $(this).attr("data-subchap");
update_right();
}
);
});

How to keep the selected menu active using jquery, when the user comes back to page?

I have a typical menu structure -
<Ul class="nav">
<li>Menu1</li>
<li>menu2</li>
-------
</ul>
When I click on certain menu, as per my jquery written on load of layout.html, it selects particular menu.
<script>
jQuery(function(){
jQuery('.nav>li>a').each(function(){
if(this.href.trim() == window.location)
$(this).addClass("selected");
});
</script>
But on that page if I click on certain link which takes me on some other page and then when I come back the menu item does not remain selected.
How can I modify my jquery to achieve this?
Thanks in advance !
As SJ-B is saying, HTML5 Web Storage is a good solution.
If you don't intend to click more than one or two pages away from the page with your list menu, you could add a query to the link that takes you away form the page e.g. the id of one of your list menus.
href="somepage.html could become something like this href="somepage.html?menu_id=menu5
When using window.history.back(), you could then fish the id out of the URL using window.location.search and use id to select the list menu.
You can use simple css code. Use active attribute like
a:active
{
//Some style
}
You can use below code to achieve this.
var lastele=siteurl.substring(siteurl.lastIndexOf("/")+1);
jQuery(".nav>li> a").each(function(){
var anchorhref=jQuery(this).attr("href");
var finalhref=anchorhref.substring(anchorhref.lastIndexOf("/")+1);
if(finalhref==lastele){
jQuery(this).addClass("selected");
}
});
I would do something like this :
<ul class="nav">
<li id="home">Home</li>
<li id="contact">Contact</li>
</ul>
Javascript :
// http://mywebsite.com#home
// location.hash === '#home'
jQuery('.nav ' + location.hash).addClass('selected');
Try to use Session Object of HTML5.
sessionStorage.varName = id of selected item.
on load just check if the sessionStorage.varName has value or undefined, if not then get the value
`var value = sessionStorage.varName;` and set it.
Well there could be many ways, on which is this which i like and always use:
It works when you path name is same as your link name For e.g. yourwebsite.com/Menu1
function setNavigation() {
var n = window.location.pathname,t;
n = n.replace("/", "");
t = $("ul li:contains(" + n + ")");
t.addClass("active");
}
You can than define styling in your active class as you like.
I stumbled upon this when googling for something similar. I have a JQueryUI accordion menu. My menu is in an included script (classic asp), so it is on every page but I think it is a similar situation. I cobbled something together based on SJ-B's answer (don't know why it was down voted).
I have this:
function saveSession(id) {
if (window.sessionStorage) {
sessionStorage.activeMenu = $("#jqmenu").accordion("option", "active") ;
sessionStorage.activeLink = id ;
}
}
and this
$(function() {
//give every li in the menu a unique id
$('#jqmenu a').attr('id', function(i) {
return 'link'+(i+1);
});
var activeMenu = 0;
var activeLink = "";
if (window.sessionStorage) {
activeMenu = parseInt(sessionStorage.activeMenu);
activeLink = sessionStorage.activeLink;
}
$("#" + activeLink).parent().addClass("selectedmenu");
$("#jqmenu").accordion({collapsible: true, active: activeMenu, heightStyle: "content", header: "h3"});
$("#jqmenu a").click(function() { saveSession($(this).attr('id')); });
});
OK, a bit untidy and cobbled together from various suggestions (I'm still learning), but it seems to work. Tried on IE11 and Firefox. Chrome can't find localhost but that's another story.
add lines below
<script>
$(function(){
$("a[href='"+window.location+"']").addClass("selected");
});
</script>
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
$('.nav li').each(function () {
if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
$(this).addClass('active');
}
});

Old Jquery filter not working in latest version1.7.2

I have working copy of tab navigation in my application, i tried to update the jquery to latest(1.7.2) , for this i have downloaded jquery-1.7.2.min.js from jquery website . After updating this the following line not working as expected tabContainers.hide().filter(':member').show();
here is the full jquery method.
$(function () {
var tabContainers = $('div.tabs > div');
tabContainers.hide().filter(':member').show();
$(window).bind('hashchange', function () {
var hash = window.location.hash || '#member';
tabContainers.hide();
tabContainers.filter(hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$('a[hash=' + hash + ']').addClass('selected');
document.getElementById("submitform").action="newaction.action"+hash;
});
$(window).trigger( "hashchange" );
});
here is the html part
<ul class="tabNavigation">
<li>Tab1 </li>
<li>tab2</li>
<li>tab3</li>
</ul>
<div id="member">content goes here</div>
<div id="tab2 . . .
Update: changing :member to #member or :first loading the content of first div, but still the first li is not got selected.(members tab)
First: With a working hashchange handler, the line tabContainers.hide().filter(':member').show(); will be nullified when $(window).trigger("hashchange"); fires. Any attempt to fix tabContainers.hide().filter(':member').show(); is therefore futile and the statement can be deleted.
Second: There's a cross-browser issue with location.hash, namely that some browsers return a string with a leading '#' and some don't. This requires the returned string to be normalized.
Taking these factors into account, you might like to try:
$(function() {
var tabContainers = $('div.tabs > div'),
submitform = $("#submitform");
$(window).on('hashchange', function () {
var hash = (location.hash=='' || location.hash=='#') ? '#member' : location.hash;
var hashNormalized = (hash.match(/^#/)) ? hash : '#'+hash;
tabContainers.hide().filter(hashNormalized).show();
$('div.tabs ul.tabNavigation a').removeClass('selected').filter(function() {
return this.hash == hashNormalized;
}).addClass('selected');
submitform.attr('action', 'newaction.action' + hashNormalized);
}).trigger('hashchange');
});
Tested in Opera 11.64 and IE9. Be sure to test in FF
See DEMO
The .filter(function(){...}) approach to filtering the anchors should immunise you against differences between jQuery versions.
Check this fiddle
.With 1.3.2 and older version only filter('#id') works but not filter(':id').I am not sure how it worked for you.
Update tabContainers.hide().filter(':member').show(); to tabContainers.hide().filter('#member').show();
You have to use either this
tabContainers.hide().filter('#member').show();
or
tabContainers.hide().filter(':first').show();
To show the first div with id member.
And to highlight the corresponding a
Change this
$('a[hash=' + hash + ']').addClass('selected');
To
$('a[href=' + hash + ']').addClass('selected');
As hash is not the attribute name, it's href.

jQuery - nth child and slider problem?

There is a generic image slider (nivo image slider) used on the charity pages that contains 7 slides, each slide is a different charity. I have used some jQuery so that when you are on a charities detail page, that specific charities slide shows up first in the slider queue; instead of it just looping from the start of the slider queue and showing a non-relevant charity. Basically looks at the URL and matches to the href in the slider link and adds a class then moves to the top of the link etc...
For example, these 2 work fine...
http://test.clothesaid.co.uk/partner-charities/yorkshire-cancer-centre/
http://test.clothesaid.co.uk/partner-charities/nspcc/
...they load their respective charities slider. However...
http://test.clothesaid.co.uk/partner-charities/papworth-hospital-charity/
...which is the oldest entry and at the bottom of the list won't load it's respective slider and just shows the slider list in it's normal order as the jQuery has not kicked in.
The charities are added in date order with the newest charity at the top of the list and the oldest charity at the bottom of the list. The jQuery works fine on all charities apart from whatever charity is at the bottom of the list, it just won't kick in. I'm sure it's something to do with the 'clone' slide that the Nivo slider uses and something to do with the :nth child in jQuery but I just can't work it out. That's the only thing that would make sense as the date order of the charities is the only thing that is changing. You can see the stack of charity logos on the right hand side of the page, that is the date order, with the oldest at the bottom. It's always the oldest one (at the bottom of the list) that won't work.
I'm basically stuck!
HTML
<ul id="slider1">
<li class="panel cloned">Example</li>
<li class="panel hello">Example</li>
<li class="panel">Example</li>
<li class="panel">Example</li>
<li class="panel">Example</li>
<li class="panel cloned">Example</li>
</ul>
jQuery
var url = window.location.toString();
$('#slider1 li.panel a').each(function(){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello').insertAfter("#slider1 li:nth-child(1)");
return false;
}
});
What's happening is that 'papworth-hospital-charity' is the first in the list of li and insertAfter will try to insert it after himself which is not working
I suggest that you check the index of the li before moving it (you are moving the target li to the 2nd position right?)
var url = window.location.toString();
$('#slider1 li.panel a').each(function(index){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello')
if(index==0){
$(this).closest("li").insertAfter("#slider1 li:nth-child(2)");
}else{
$(this).closest("li").insertAfter("#slider1 li:nth-child(1)");
}
return false;
}
});
or use anythingSlider ability to show slides by index:
var url = window.location.toString();
$('#slider1 li.panel a').each(function(index){
var myHref= $(this).attr('href');
if( url == myHref) {
$('#slider1').anythingSlider(index);
return false;
}
});
$(document).ready(function() {
var url = window.location.toString();
$('#slider1 li.panel a').each(function(){
var myHref= $(this).attr('href');
if( url == myHref) {
$(this).closest("li").addClass('hello').insertAfter("#slider1 li:nth-child(1)");
return false;
}
});
};

Categories

Resources