Make scrollTo make div scroll all the way? - javascript

I have a div with only horizontal overflow. With a link outside the div, I'm trying to scroll the div to a certain image (think of a horizontal gallery scrolling to the right).
I used the following javascript. It works fine in the webpage.
However, the DIV containing the gallery is larger than most images. Consequently the browser window will scroll only until the requested div comes in from the right and is now fully on screen, and not one pixel more. However, I would like the div to scroll all the way, so that the image is all the way hugging the left edge of the container.
I hope I'm making sense, I'm not terribly experienced, but I couldn't find an answer to my question online.
$(document).ready(function(){
$('#gimg1').click(function() {
$.scrollTo($('#gimg1link'), 1000);
});
$('#gimg2').click(function() {
$.scrollTo($('#gimg2link'), 1000);
});
$('#gimg3').click(function() {
$.scrollTo($('#gimg3link'), 1000);
});
$('#gimg4').click(function() {
$.scrollTo($('#gimg4link'), 1000);
});
});
<div id="gallery">
<img class="galleryimage" id="gimg1" src="lb1.jpg">
<img class="galleryimage" id="gimg2" src="lb2.jpg">
<img class="galleryimage" id="gimg3" src="lb3.jpg">
<img class="galleryimage" id="gimg4" src="lb4.jpg">
</div>
Image 1
Image 2
Image 3
Image 4

You are using the image and link selectors in your jquery in the wrong order.
$('#gimg1').click(function() {
$.scrollTo($('#gimg1link'), 1000);
});
This snippet means "when the image #gimg1 is clicked, scroll to the position of the link #gimg1link". You want it the other way round: when the link is clicked, scroll to the image.
Reversing those selectors gives you a working slider: jsFiddle
The last image will always stay on the right of the screen, because that's where the document ends and it can't scroll any further. The other images will scroll all the way to the left as long as your document width allows it.
Also, you could optimize your javascript a lot by not copy-pasting the same code but just making it more generic:
$(document).ready(function(){
$('a[id^=gimg]').click(function() { // when a link with an ID starting with "gimg" is clicked
var linkID = $(this).attr('id'); // get the whole id from this link
var imgID = linkID.replace('link', ''); // get the img ID it relates to by removing the 'link' part
$scrollTo( $('#' + imgID), 1000); // scroll to the image this link belongs to
});
});
Now it doesn't matter how many links and images you add, as long as they all use the same naming convention.

Based on this answer i adapted the code to suit your need. It uses the clicked thumbnail index to find the corresponding image left, and set scrollLeft of the viewport to this value.
$('#nav li').click(function(){
var clickedIndex = $(this).index();
var targetElement = $('#viewport ul li').eq(clickedIndex);
var elementPosition = targetElement.position();
$('#viewport').animate({scrollLeft: elementPosition.left},500);
});
Working fiddle: http://jsfiddle.net/Lqvqtwtb/

Related

menu items getting highlight as I scroll to each section with deficiency

I just used this code to get my menu highlighted as I scroll down to each each section of my WordPress site:
(function($) {
$(document).ready(function(){
$("header nav ul").toggleClass("open");
$("section.container").addClass("section");
});
$(window).scroll(function() {
var position = $(this).scrollTop();
$('.section').each(function() {
var target = $(this).offset().top;
var id = $(this).attr('id');
if (position >= target) {
$('#primary-menu > li > a').removeClass('active');
$('#primary-menu > li > a[href=#' + id + ']').addClass('active');
}
});
});
}(jQuery));
css:
.active{
color: #fff !important;
}
Here is the link: http://scentology.burnnotice.co.za
Problem is that the last item(Contact) is not getting highlighted when I scroll all the way down up to contact section.
Also,if I click on a menu item,it goes to the respective section but that menu doesn't get highlighted unless I scroll the page a little bit down'.
How can I solve that?
Thanks in advance
NOTE: It seems that you took that code from my answer to this SO question, I have edited it to cover your case. Other people looking for more code can check it out for a snippet.
So, you have two problems:
The last item is not getting highlighted.
When clicking on a menu item, the page scrolls to the respective section but that menu doesn't get highlighted unless scrolling down the page a little bit.
Problem 1
This one is easy, you just forgot to add the id attribute to the last section :)
It should be:
<section id="contact" class="container contact-us section">
Problem 2
Your click event starts a scroll animation to the corresponding section but, since the navigation bar is on the top of the page, you made the animation to leave a little margin on the top. That margin prevents the section from reaching the top of the page, so the menu item doesn't get highlighted.
#Shnibble pointed you in the right direction, you can add a small positive margin to the value returned by $(window).scrollTop() (or a negative one to the offset().top of the element).
So, following the code you have included, it will be something like:
if (position + my_margin >= target) {
The margin could be the height of your navigation bar:
my_margin = $('#site-navigation').height();
You can, obviously, add a little more or less to tailor it to your needs.
There is a simple solution and it just requires a bit of additional math :)
You are measuring from the top of the (window) viewport and checking to see if it is greater than or equal to the top of a specified target div. Because your content sections are exactly 100% of the viewport, it is impossible for the top of the viewport ever be greater than or equal to the top of the last content div.
What you need to do is offset the point you are measuring from so that you are not measuring from the top of the viewport, but rather some ways down from the top, say halfway or 3/4 of the way down. This will solve both of your issues.
Edit: here is something to get you started, then play around with dividing the window height by 1/2 or something like that:
var position = $(this).scrollTop() + $(window).height;

Scale and change an element from an image to a word, depending on scroll position.

I have seen some scrolling effects for example on Google SketchUp's site, their banner is initially "built into the page" and then it seems to pop out and remain stuck at the top after a certain position down (scrolling).
Google Plus seems to have some special effects as well, like changing the banner entirely once the scrolling has reached a certain position.
Attached is what I am trying to accomplish. A square logo is on the right, and then when the page is scrolled down, the logo starts to scale to the same height as the banner/header / fade and then becomes a word rather than the image.
What am I looking at here? jQuery or javascript? How do I track the scrolling and connect the two?
Is it what you want to achieve?
http://jsfiddle.net/agdbd8x6/15/
If so, it is quite easy. If you use jQuery, attach 'scroll' event handler and check current scroll position. Show the image only with zero scroll position:
var img = $('#image');
var txt = $('#text');
$(".container").scroll(function(){
txt.text('Scroll position = ' + $(this).scrollTop());
var showImage = $(this).scrollTop() == 0;
if (showImage){
img.css('display', 'inline');
txt.hide();
}
else{
img.hide();
txt.css('display', 'inline-block');
}
});

Making an image appear after scrolling past header - attempts not working?

I've recently taken over work on a friend's website, here. I want to get the small logo above the description box to only show up once the user has scrolled past (and subsequently hidden) the large header at top, and disappear again if the user scrolls back up past it. I've tried the methods recommended in these other posts here and here, which seem like the same basic idea but I can't get any of them to work.
I'm new to anything and everything scripting (which I'm entirely sure is the biggest problem here, I know.) So any help is appreciated as what I'm apparently doing wrong.
Start by giving the <div class="fixeddiv"> a style="display: none". Then add the following (since you're already using jQuery):
$(document).ready(function () {
var contentOffset = getOffset();
function getOffset() {
var allOffsets = $("div#content").offset();
return allOffsets.top;
}
$(window).resize(function () {
contentOffset = getOffset();
});
$(window).scroll(function () {
var windowTop = $(window).scrollTop();
if (windowTop > contentOffset) {
$("div.fixeddiv").show();
} else {
$("div.fixeddiv").hide();
}
});
});
Here's what this code does. When the document is done loading, it gets the number of pixels that the "content" div is from the top of the document (offset). It does this again any time the window is resized. Then, when someone scrolls up or down, it gets the number of pixels that are already hidden above the scroll (scrollTop). If the number of hidden pixels is greater than the offset of the #content div from the top of the window, that means we've scrolled past the top of the content div and should show the icon. Otherwise, we should hide the icon.

Display image on top of page with big 3 + jquery, in FireFox?

Would like to bring a single image to the front or on top of the page, when selected.
After searching, it seems there are many plug-ins that support this - but also have a lot of other functionality and overhead I don't need (gallery, support for video, thumbnails, etc.)
Is it possible to just bring a single image on top with basic JavaScript, CSS, HTML and jQuery, specifically in FireFox?
Thank You.
(Please note*: This is an in house product, hence these requirements and constraints.)
Is it possible to just bring a single image ontop with basic JavaScript, CSS, HTML and jQuery, specifically in FireFox?
Yes, it's possible, but the plugins are most of the time an easier implementation. What you are trying to accomplish is something similar to the light box effect, but I'll try to give a simple solution based on 4 steps you need to accomplish what you are trying to do:
Create an overlay div. This one div will blur or darken your entire page. In the below example it will darken your screen (because it's simpler).
Create an div that will be appended to the overlay div and will contain the image you want to show. In the demo below, this div will be lighter than the overlay one and will actually have half the width and half the height of your screen.
Append a bigger image to your image-div.
Add a subtitle to your image based on it's alt text.
$(document).ready(function()
{
var docWidth = $(document).width();
var docHeight = $(document).height();
//First Step" Creating the overlay-div and adding opacity to it
var overlayDiv = "<div id="overlay-div"></div>"
$("body").append(overlayDiv);
$("#overlay-div").css("position","absolute", "top","0","left","0","background-color","#000","opacity","0.5", "width", docWidth + "px", "height",docHeight + "px");
//Second step: Creating the image-div and centering it on the screen
$("#overlay-div").append("<div id=\"image-div\"></div>");
$("#image-div").css("position","absolute", "top",docHeight/4 + "px","left",docWidth/4 + "px","background-color","#FFF", "width", docWidth/2, "height",docHeight);
//Third step: Creating an image to display inside the image-div and centering it
$("#image-div").append("<img src=\"path/to/your/image\"id=\"zoomed-img\" alt=\"This is a zoomed image\"/>");
var imgWidth = $("#image-div").width();
var imgHeight = $("#image-height").height();
$("#image-div").css("position","absolute", "top","10px","left","10px");
//Fourth step: Creating a subtitle from the alt text
var subtitle = "<p id=\"text-subtitle\">" + $("#image-div").attr("alt") + "</p>";
$("#image-div").append(subtitle);
$("#text-subtitle").css("position","absolute", "top",imgHeight + 20 + "px","left","10px");
});
This function is triggered when your document is ready, and get an arbitrary image. But it's possible to display a different image (with a different subtitle) triggered by a click with a little tweak of the code above.
I had the intention to show you a simple demo that it's feasible to with with a few lines of jQuery/javascript code to create what you want. Of course it's not as pretty as 90% of the effects of the plugins there are around but it may be a start.
I hope it helped. Cheers
Here is a very basic example I whipped up. Hopefully good to learn from:
http://jsfiddle.net/v9LTP/2/
$('img').click(function(){ //bind a click event handler to images
var img = $(this).clone().addClass('modal').appendTo($('#blackout')); //clone the clicked image element and add to the blackout div which gives the dark background.
$('#blackout > #close').click(function(){ //attach click handler to close button
$('#blackout').fadeOut(function(){ //fade the blackout div
img.remove(); //remove the image element we cloned, so we can do it again.
});
});
$('#blackout').fadeIn(); //show the blackout div
});
​
For a stupid simple lightbox I've been leveraging http://buckwilson.me/lightboxme/ lately.
Try Modals of Bootstrap.
JavaScript - Twitter Bootstrap
GitHub source code
GitHub bootstrap-modal.js

Div width expand/shrink on click

For a site I'm making for myself and a friend, I have a div container/wrapper with 2 other divs within it: one occupies the left half and has a black background and the other occupies the right with a white background. Essentially, this lets me get a split colored background. Each div holds half of a logo. Here's the page, temporarily hosted so you guys can see it.
http://djsbydesign.com/tempsite/index.htm
At any rate, I'd like to have links on the left and right hand sides of the page that, on click, cause their respective divs to expand from 50% to 100%. I have a few ideas, but am not sure entirely how to go about doing this (I'm rather new to javascript). The first would be to have the expanding div's z-index set to something higher than the non-expanding one, and then have it expand (somehow), and the other is to have the expanding div expand to 100% while the other shrinks to 0% at an equal rate.
The bottom line is, I have no idea how to go about doing this. I don't mind using mootools or jQuery, for the record.
The following seems to work:
$('#left-bg, #right-bg').click(
function(){
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
});
Albeit I'm not sure how you'd plan to bring back the the 'other' div.
JS Fiddle demo.
Edited to add a button (via jQuery) that allows both divs to be reverted to original dimensions:
$('#left-bg, #right-bg').click(
function(){
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
$('<button class="show">Show all</button>')
.appendTo('#wrapper');
});
$('.show').live('click',
function(){
$('#left-bg').animate(
{
'width': '50%'
},600);
$('#right-bg').animate(
{
'width': '50%'
},600);
$(this).remove();
});
Updated JS Fiddle.
Edited to address the question left by OP in the comments:
is there a way to have a page redirect after the animation completes?
Yep, just add the line window.location.href = "http://path.to.url.com/";
$('#left-bg, #right-bg').click(
function(){
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
$('<button class="show">Show all</button>')
.appendTo('#wrapper');
window.location.href = "http://www.google.com/" // <-- this line redirects.
});
$('.show').live('click',
function(){
$('#left-bg').animate(
{
'width': '50%'
},600);
$('#right-bg').animate(
{
'width': '50%'
},600);
$(this).remove();
});
Updated JS Fiddle.
Edited in response to bug report (in comments):
The one other bug (easy fix) is that any time you click on either of the divs, it creates a new button. So say you clicked on the left half, and it expanded and filled the page, etc., and then you clicked on it again (it being anywhere on the page now). It would attempt to add a second button.
To prevent a second button being added to the div just add an if:
$('#left-bg, #right-bg').click(
function(){
if (!$('.show').length) {
$(this).animate({'width': '100%'},600).siblings().animate({'width':'0'},600);
$('<button class="show">Show all</button>')
.appendTo('#wrapper');
window.location.href = "http://www.google.com/" // <-- this line redirects.
}
});
Which, will only append a button, or indeed animate the divs, so long as the $('.show') selector returns no matches.
However if you're also redirecting to another page by clicking the button it shouldn't be an issue anyway, since none of the jQuery on the original page will exectute/be able to access the page to which the user is redirected (unless it's a page on your own domain, and you've explicitly chosen to add the same button).
If you give absolute positions to your div's such that - 1st is positioned at top left corner and other is positioned at top right corner. And then in click event you can change the position of the other top corner of the div to be expanded.
You can use jquery to do this easily. Check jquery documentation for setting css.
Looks like you've got jQuery included, so use that! It's totes the easiest library to do simple animations with.
Here's an example click function that will slide the right background to be 100% like you said:
$('a#link').click(function(e) {
e.preventDefault();
$('#left-bg').animate({ width : '0%' }, 'slow');
$('#right-bg').animate({ width : '100%' }, 'slow');
});
Obviously to go in the other direction you'd switch the width values in the object passed to the animate functions.
If you're not familiar with the animate function, check the docs, but basically you just pass CSS rules in a key : value object to it, and it'll change the CSS values over time - animating it!
Hope this helps!

Categories