Scrollspy offset for a button - javascript

I have a fixed navbar, so I need a little offset when a certain element in the navbar is clicked, for which I used this code (It works perfectly fine for the navigation bar elements) :
var offset = 68;
$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});
But I have two buttons that also link to certain sections of the website:
<div id="main">
<img src="images/face.png" class="logo">
<div id="promo">
<h2> So, your website doesn't look good anymore? <br><h3> We'll give it a second breath, then support you along the way.</h3></h2>
</div>
<div id="buttons">
<a href="#portfolio"><button id="portbut">
View portfolio
</button></a>
<a href="#contact"><button id="quotebut">
Get a quote
</button></a>
</div>
</div>
But when I place their id's in the js code I mention above, it's not working, the offset is not taken into consideration when "moving" to a certain section of the website.
What should I edit so the offset would be taken into consideration for those two buttons ?

If someone ever needs it, the answer is:
var offset = 68;
$('#buttons a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});

Related

I need javascript on one page to influence elements on a different page

I'm using javascript to control where my page page scrolls to after clicking on an anchor link, as I have a fixed nav.
I have one page that the anchors + script work correctly on (PAGE B). My issue is that I have buttons on a different page (PAGE A) that need to go the anchors on the correctly working page (PAGE B). The anchor itself works correctly, but the javascript does not fire.
The reason why it's not firing (tested by putting an alert and not receiving a popup) is because the javascript for the buttons on PAGE A does not know to look for the element on PAGE B. After googling for three hours I cannot figure out how to tell it to look at a new page instead of just the hierarchy of elements. I'm sure this is stupidly simple, but I'm a beginner at javascript and appreciate the help.
The code:
PAGE A Button HTML:
<a href="productsandservices.html#financing" class="btn btn-sm btn-default
actively2">Learn more</a>
PAGE A Javascript:
<script>
$("div ul li a[href^='productsandservices.html#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 150
}, 300, function(){
});
});</script>
PAGE B Anchor HTML:
<div class="col-md-10 col-md-offset-1 col-sm-12 col-xs-12"><section id="financing">
PAGE B: Javascript: (the exact same as PAGE A)
$("div ul li a[href^='productsandservices.html#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 150
}, 300, function(){
});
});</script>
Please and Thanks.
Page B will never be able to respond to a click event on the previous page, which seems to be what you're trying to do in the code.
Try using location.hash to access the hash instead.
$(window).on('hashchange', function(e) {
$('html, body').animate({
scrollTop: $(location.hash).offset().top - 150
}, 300);
});
I also came up with a different solution.
I moved added a names, and placed them at the end of the previous div before the section id. Then I added some extra padding to each header of the anchor. This way, I can smoothly travel to an anchor on a different page. Arguably, this does not solve my javascript issue, but it can count as (not too badly) hacked work-around.
Not sure the contribution was worth it but as I'm always asking and never giving solutions as I'm still learning I figured I could at least answer my own question!
Basically, instead of having
<div class="a">
<section id="a"><h2>Title</h2></section>
<p>yadda yadda</p>
</div>
<div class="b">
<section id="b"><h2>Title</h2></section>
<p>yadda yadda</p>
</div>
<div class="c">
<section id="c"><h2>Title</h2></section>
<p>yadda yadda</p>
</div>
I added 30px of padding to each div in the css:
div.a, div.b, div.c {
padding:30px 0px;
}
And added a names to the section above the div in question, like so:
yadda yadda
<div class="a">
<section id="a"><h2>Title</h2></section>
<p>yadda yadda</p>
<a name="#b"> </a>
</div>
<div class="b">
<section id="b"><h2>Title</h2></section>
<p>yadda yadda</p>
<a name="#c"> </a>
</div>
<div class="c">
<section id="c"><h2>Title</h2></section>
<p>yadda yadda</p>
</div>
I understand the a name is depreciated using HTML5, but drupal 7 has an issue with recognizing relative anchors. This also solved that issue.

Scroll to queued divs on click

I'm sure this is a pretty common question around here but after lots of research I can't seem to find an answer to my question.
So just a little warning; I'm really new into javascript and jQuery etc.
To the question! I'm trying to apply two images (It's img's that looks like buttons :P) which you click on and it scrolls to the "next" paragraph or div.
So to get an overview of how it looks, here' a part of the HTML:
<div id="scrollbuttons">
<img id="prev" src="pics/prev.png"></img>
<img id="next" src="pics/next.png"></img>
</div>
Also:
<div id="work">
<p class="maintext">blabla</p>
</div>
<div id="gallery">
<p class="maintext">blabla</p>
</div>
<div id="project">
<p class="maintext">blabla</p>
</div>
<div id="finish">
<p class="maintext">blabla</p>
</div>
So what I'm trying to create is when you click on "next", the page should smoothly and automatically scroll to firstly, "work", then to "gallery" etc.
And when you press "prev", the page should again smoothly and automatically scroll back to the previous point.
I have the latest jQuery version and I'd like to not install plugins if it's not absolutely needed.
So I hope this is enough info to get some help, I'd really appreciate it since I'm really new to JS.
Thanks in advance
/Emil Nilsson
Here you go, this could probably be done a little more efficiently but it's dynamic and it works. Click the buttons to go forward and backward. FYI I added a mutual class called section to all of your content divs
JSFIDDLE
var Section = "start";
$("#next").click(function(){
if(Section == "start"){
var nextSection ="work";
}else{
var nextSection = $("#"+Section).next(".section").attr("id");
}
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
$("#prev").click(function(){
var nextSection = $("#"+Section).prev(".section").attr("id");
$("html, body").animate({scrollTop: $("#"+nextSection).offset().top});
Section = nextSection;
});
maybe you need something like this
http://jsfiddle.net/urUFK/
the img would be inside of the anchor like this (semantics and W3C validation):
<img id="prev" src="pics/prev.png"></img>
on my version you just need to define the first element and the div id's

Setting `a href` elements dynamically

I have two buttons that are essentially "next" and "previous" buttons for my tabbed form with bootstrap. The code works when you go from the introduction tab to the applicant tab just fine the way it is. The only problem is there are 11 "tabs" in the element. I am needing essential parts in this <a> to change on each tab.
What I am needing to change is the href , .style.width , and the two classNames at the end of the `onclick' function each time the user progresses through the form.
Previous
Next
The sections that need to correspond with the buttons are identified with an id that is different for all 11 sections.
<div class="tab-pane" id="confirmation">
So for example when the users clicks the button "next" from the introduction tab I need the above to change to: (and vise versa for the previous button)
Previous
Next
and so on throughout the tab-panes.
I am figuring I could do something like, I just really don't know how to start it and how to change just the specific onclick elements like I am needing to.
if(this tab-pane is something?)
{
document.getelementById('previous').href="";
document.getelementById('previous').style.width="";
document.getelementById('previous').className="";
}
As Requested in the comments the tabs are laid out like so:
<div class="tab-content">
<div class="tab-pane" id="introduction">
//content here
</div>
<div class="tab-pane" id="applicant"> //and so on just like this for all 11 tabs.
//content here
</div>
</div>
Here you go...
This is using Twitter bootstrap and Jquery...
Hopefully its helpful to you...
The progress bar is a bit of a hack, but its a start and Im sure you can figure things out from there...
The only thing that sucks is that the tabs are clickable, and that isn't what you wanted, since you want them to progress through the form without being able to click on the tabs....But the nuts and bolts are here
DEMO HERE
$(document).ready(function(){
//Progress bar calculation
function setProgress(){
var length = $tabs.length;
var index = ($('li').index($(".active")))+1;
var width = (index/length)*100;
$('#progressBar').css('width', width+'%');
}
var $tabs = $('#tab_bar li');
setProgress();
$('#prevtab').on('click', function () {
$tabs.filter('.active').prev('li').find('a[data-toggle="tab"]').tab('show');
setProgress();
});
$('#nexttab').on('click', function () {
$tabs.filter('.active').next('li').find('a[data-toggle="tab"]').tab('show');
setProgress();
});
$tabs.click(function () {
setTimeout(setProgress, 200)
});
});
Then your HTML, I dunno what you had for < ul > , cuz you didn't provide that part... so I just hacked something up...but this should be similar to your structure
<ul class="nav nav-tabs" id="tab_bar">
<li class="active">Intro</li>
<li>SecondTab</li>
<li>Third</li>
<li>Fourth</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="introduction">
asdasdasdas
</div>
<div class="tab-pane" id="secondtab">
asdasdsagreteryterythhgh
</div>
<div class="tab-pane" id="thirdtab">
rthrthrthrthrt
</div>
<div class="tab-pane" id="fourthtab">
yujghjuyjyujedgjhegj
</div>
</div>
<a class="btn" id="prevtab" type="button">Prev</button>
<a class="btn" id="nexttab" type="button">Next</button>
DEMO HERE

Inserting padding to compensate for "scrollbar jump"

I have a horizontally centered container with a navbar that hides and shows divs of varying length with js. Sometimes, if the content in the shown div is too long, showing the div will also show a scrollbar and cause the page to "jump" to the left in certain browsers. The CSS is just Bootstrap's basic scaffolding.
Below is the gist of what's going on in the site. but you can see the problem in production here: http://dylanpatrickclark.com
<body>
<script type="text/javascript">
$(document).ready(function(){
function setNavState(currentHash) {
$('nav ul li').removeClass('active');
var selector = 'nav ul li a[href="' + currentHash + '"]';
$(selector).parent().addClass('active');
};
function hash() {
var hash = window.location.hash;
if (hash != ''){
$('.tabs div').hide();
$(hash).show();
}
else {
$('.tabs div').hide();
$('.tabs div#tab1').show();
hash = 'tab1'
}
setNavState(hash);
};
hash();
$(window).bind('hashchange', function() {
hash()
});
});
</script>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<nav>
<ul>
<li> Tab1 </li>
<li> Tab2 </li>
</ul>
</nav>
</div>
</div>
<div class="row">
<div class="tabs">
<div class="tab-pane" id="tab1">
<p>Short</p>
</div>
<div class="tab-pane" id="tab2">
<p>Long</p>
</div>
</div>
</div>
</body>
I have seen a lot of older answers to this question here, a lot of them suggest forcing the scrollbar to show, but I'd rather use js to insert padding to compensate for the scrollbar. I think facebook does something like this. I'm not really want to worried about IE support, as I am mostly focusing on finding a solution that I can understand with my rudimentary understanding of javascript.
Can anyone explain simply how to best compensate for the appearance/disappearance of a scrollbar with javascript?
Thank you so much!
Two ways come to my mind, first you can define body { overflow:scroll } for preveting sliding with scroll or second you can create your own scroll with scrollbar plugin and define scrollbar's css { position: absolute; right:0px; }. Note: relative to body or wrapper ofcourse.
body {overflow-y:scroll} worked perfectly for me when I had this issue

Fade in/out js mouseover event

I am looking to implement a mouseover event on my page for a menu -
I have 3 titles to the left with a respective content div on the right where the related text appears.
Having trauled all the forums for a working js solution, I have settled with:
http://flowplayer.org/tools/demos/tabs/mouseover.html
which uses a very simple js function:
$("#products").tabs("div.description", {event:'mouseover'});
What I am hoping to do however, is to incorporate a fadeIn(), fadeOut effect so that when the user hovers over a title on the left of the page, the existing content showing fades away and the repective content will fade in to view......
The html coding is:
<div id="products" >
<img src="home.png" alt="home" />
<img src="services.png" alt="services" />
<img src="contact.png" alt="contact" />
</div>
<div class="description" id="home" >
.. content ..
</div>
<div class="description" id="services" >
.. content ..
</div>
<div class="description" id="contact" >
.. content ..
</div>
I have tried to incorporate thread 5404775 on this site but simply cannot get it working!
Any help much appreciated
The below can be seen on jsfiddle.
You can fade them in and out on mouseover like this
var _current = "home"; // default state
$('#products img').mouseover(function (){
// The one we want to show now
var id= $(this).attr('alt');
// We don't need to do anything if it's the same one that's already
// there
if (_current !== id){
$('#' + _current).fadeOut(function(){
// Fade in the new one after the old fades out
$('#' + id).fadeIn();
// Update state
_current = id;
});
}
});
I also added some thing to make sure that only the one you want displayed first is displayed when the page loads. I'm assuming it would be the home div.
Add this to the CSS
.hidden{
display:none;
}
and put that class on the other divs.
<div class="description hidden" id="services" >
.. services..
</div>
<div class="description hidden" id="contact" >
.. contact ..
</div>
I'm working off the assumption that you want people hovering over the image buttons here to make the corresponding divs fade in and out. What they are doing on that site will not work because Javascript is needed for the fading effect. JQuery makes this easy.
I recommend trying something like
<script type="text/javascript">
oldSelected = "home"
$(document).ready(function(){
$("#products img").mouseover(function(){
$(".description").stop(true, true);
var newSelected = $(this).attr("alt");
$("#" + oldSelected).fadeOut('normal',function(){
$("#" + newSelected).fadeIn();
});
oldSelected = newSelected
});
});
</script>
I have tested this and it works. One thing you will want to make sure of is that the css for the divs has them set to not be visible at the start, unless you want one of them visible in which case the id for that div should be what you set the oldSelected to at the start of the function.
Enjoy!
This might work:
$("img", "#products").hover(function() {
var id = $(this).attr("alt");
$("#" + id).fadeIn("slow");
}, function() {
var id = $(this).attr("alt");
$("#" + id).fadeOut("slow");
});
Another idea (without Jquery): you could use CSS opacity:x property (for firefox) or filter:alpha(opacity=x) (for IE) to change the opacity of an element. Fade in/out can be obtained with a small slowed-down cycle.
See also:
http://www.w3schools.com/css/css_image_transparency.asp

Categories