Smooth scrolling onclick of li element - javascript

I'm trying to write jQuery code which would make the page scroll to the div instead of going there immediately and to make it as simple as possible. I have added ids of desired divs to li elements.
My html code looks like this:
<li id="#slide1" class="active" onclick="javascript:location.href='#slide1'"><a href="#slide1" title="Next Section" >About</a></li>
<li id="#slide2" onclick="javascript:location.href='#slide3'">Works</li>
<li id="#slide3" onclick="javascript:location.href='#slide3'">Contact</li>
<li id="#slide4" onclick="javascript:location.href='#slide4'">belekas</li>
<li id="#slide5" onclick="javascript:location.href='#slide5'">dar vienas</li>
and I tried this jQuery code but it doesn't work. So maybe anyone could help me?
$('li').click(function(){
var target = $(this).attr('id');
$("html, body").animate({
scrollTop: target.offset().top
}, 1000);
return false;
});
UPDATE: https://jsfiddle.net/j452hL2w/ here's is fiddle version of my navigation

I removed every onclick="javascript:location.href='#slide'" from every list item. This is not necessary because you create the clickhandlers in javascript.
I replaced your click function with this:
$('li').click(function(e) {
// Prevent default action (e.g. jumping to top of page)
e.preventDefault();
// Create a variable with the link found in the list-item
var link = $(this).children('a');
// Animate the document
$('html,body').animate({
// Gets the href from the link ('slideX') and scrolls to it on the page.
scrollTop: $(link.attr('href')).offset().top
// 'slow'(600ms) can be replaced by 'fast'(200ms) or a number in ms.
// The default is 400ms
}, 'slow');
});
Here is the updated fiddle.

Related

JavaScript that adds behavior to all links should exclude some

I have the fallowing smooth scrolling script:
<!-- Smooth scroll JS -->
<script type="text/javascript">
jQuery('a[href^="#"]').click(function(e) {
jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);
return false;
e.preventDefault();
});
</script>
The problem is that it affects all link to an id (as intended) and causes a conflict with toggle script.
I need to add a condition to the script so that the links in the #work_tabs div are not affected.
<div id="work_tabs">
<ul>
<li>Films</li>
<li>TV Films</li>
<li>TV Shows</li>
<li>Special Events</li>
</ul>
</div>
I tried adding the condition myself but i'm still new to JS and have no idea how to achieve this.
How could I make the script ignore the links in the work_tabs id?
You can use the not() function:
jQuery('a[href^="#"]').not('#work_tabs > a').click(function(e) {
jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);
return false;
e.preventDefault();
});
This will exclude any anchor tags inside that div.
Read more here.
One way to go about it is add a class to the items that can be toggled and change your element selector to point to that.
jQuery('.toggle').click(function(e) {
You can use the jQuery .not() function to remove the intended elements
Use jQuery('a[href^="#"]').not('#work_tabs > a')
<!-- Smooth scroll JS -->
<script type="text/javascript">
jQuery('a[href^="#"]').not('#work_tabs > a').click(function(e) {
jQuery('html,body').animate({ scrollTop: jQuery(this.hash).offset().top}, 1000);
return false;
e.preventDefault();
});
</script>

jquery smooth scroll to an anchor in wordpress

I'm trying to implement jquery smooth scroll to an anchor after clicking the menu item in the wordpress. I'm using this example:
http://jsfiddle.net/YtJcL/
Here is the js file:
$(".anchor_scroll").click(function(event){
event.preventDefault();
//calculate destination place
var dest=0;
if($(this.hash).offset().top > $(document).height()-$(window).height()){
dest=$(document).height()-$(window).height();
}else{
dest=$(this.hash).offset().top;
}
//go to destination
$('html,body').animate({scrollTop:dest}, 5000,'swing');
});
In my wordpress page I create a section:
<section id="services"></section>
and in the wordpress custom menu put a class "anchor_scroll" to a link:
<a class="anchor_scroll" href="#services">.
After this I'm able to navigate to an anchor in the page after pressing the link, however, the jquery code seems to be not working, because there is no smooth slide effect, just jump.
Here's the code I would use for this;
$(".anchor_scroll").click(function(){
var section = $(this).attr('href');
$('html, body').animate({
scrollTop: $(section).offset().top - 15
});
});

onclick Search - jump to search results section

I would like to change the functionality of WP Casa theme Paraiba. http://wpcasa.com/demo/paraiba/
Right now the search results are displayed under the page fold - my aim is to scroll down on them after the search button is clicked.
Would you advise me how to accomplish that?
Thanks.
Try this :
$(document).on('click','.listing-search-submit', function(event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $("#main-wrap").offset().top
}, 2000);
});
NOTE : This answer depends on the link given by you.So if you have made changes to class or ID then above code won't run.

How can I load the content of tumblr nextPage on indexPage

I'm developing a tumblr theme for my personal portfolio, but I'm encountering a serious problem in my work section, I want to create an horizontal slider effect, when I click next to see older posts,
like this:
http://tympanus.net/Tutorials/WebsiteScrolling/
I have this to define my nextPage, #section4 is where I have the posts of my work:
<!-- Next Page -->
{block:NextPage}
<div>
<a id="next-button" href="{NextPage}#section4" class="next panel" style="position:relative; top:630px; left:1550px;">next</a>
</div>
{/block:NextPage}
<!-- / Next Page -->
Well, this is defined to open an other page:
"indexPage".tumblr.com#section4
when I click next it goes to:
"indexPage".tumblr.com/page/2#section4
Is there a way I can do this slide effect on my index page or at least give the illusion, that I'm making slide effect, when moving to other page?
If I understand your question correctly, it is as serakfalcon mentioned but I'll add in tumblr specific points. You need to do three things specifically. I won't go into too much tumblr template codes and styling it and stick to these
Loading the data dynamically
Dynamically creating a new section/page
Getting the navigation to work with new sections
Loading the data
This is actually the easy bit. For tumblr, as you mentioned, we can manually go to the next page by clicking the "next page" link. In tumblr this will look something like
{block:NextPage}
<li></li>{lang:Next page}</li>
{/block:NextPage}
Since the pages are on the same domain, we can override the link to get the page using AJAX. We will be getting the raw HTML for this page. Which will include all the other parts of the page like the three other sections. There may be some tumblr template magic that we can do to limit this, but I'll consider that outside the scope. So how do we get the content specifically? We can feed the raw HTML into jquery for it to build document objects, and we can then select the content that has the post from there. So something like.
$(document.body).on('click',".static",function(e){ //delegated
var xhr=$.get($(this).attr("href"),function(a){ //a is next page's HTML
$loaded=$(a); //loaded now has a temporary object with next page's objects
var postsHTML=$loaded.find("#posts").html() //contains posts we can embed
//what to find depends on your template. I used the default id="posts"
})
})
Creating a new section/page
Once we have the data, we now need to put the data into a new page. There's many ways on doing this but here's how I did it. First of all, I had a template for the new section. I put it in a script tag like so. I kind of like the semantics of doing it like this.
<script type="text/x-template" id="section-template">
<div class="section">
<div class="posts"></div>
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>Back</li>
<li>Next</li>
</ul>
</div>
</script>
With that done, whenever the data is loaded we can get the raw HTML from this, and create a the new elements by feeding it to jQuery again. We then append the posts to the div with class posts. We also get the next page link from the data to attach to the next-page link so that the earlier ajax call will work. If we can't find the next-page link, that means there's no more posts. So we can hide the next-page link. We'll also stop the existing link to load data through ajax and do the normal slidey thing. Finally we'll append the new section to the parent div of the sections, fix it's width and then transition to the new section.
$(document.body).on('click',".static",function(e){ //deferred
e.preventDefault();
var that=this //to refer inside $.get callback
var xhr=$.get($(this).attr("href"),function(a){
$(that).removeClass('static') //stop this link from loading again
var $loaded=$(a)
var next_section=$($("#section-template").html()); //make the new section
var num_sections=$(".section").length + 1 //number of sections
next_section.addClass(num_sections%2 ? "white" : "black") //consistency
//find .posts in the new section and put the tumblr data in it
next_section.find(".posts").html($loaded.find("#posts").html())
//tumblr next page link. change according to template
var next_link=$loaded.find(".static")
if(next_link.length){ //if next link exists
//attach href to next page link in new section
next_section.find(".static").attr("href",next_link.attr("href"))
} else { //no next
//hide the next page link in new section
next_section.find(".static").hide()
}
$("#horizontal-scroller").append(next_section); //append to body
$("#horizontal-scroller").width(4000*num_sections); //resize body
$('html, body').stop().animate({ //to the new section
scrollLeft: $(next_section).offset().left
}, 1000);
}) //$.get
}) //click
Getting the navigation to work
I probably should append new links to the nav, but I guess to make it easier (and imagine how it look like with 40 pages) I decided to just use a "next page" and "last page" for the loaded content. The code is simple. For next page, if it's not .static, move to the next section and ditto last page. we'll delegate (technically, I'm using .on() but the docs on .delegate seemed easier to understand) it to the document body so that it works for all the new links.
So as a whole javascript/jquery will look something like
$(document.body)
.on('click','ul.nav a:not(.next-page):not(.last-page)',function(e){
var $anchor = $(this);
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1000);
e.preventDefault();
})
.on('click',".next-page:not(.static)",function(e){ //next page not static
e.preventDefault()
$('html, body').stop().animate({
scrollLeft: $(this).closest(".section").nextAll(".section").offset().left
}, 1000);
})
.on('click',".last-page",function(e){ //last page
e.preventDefault()
$('html, body').stop().animate({
scrollLeft: $(this).closest(".section").prevAll(".section").offset().left
}, 1000);
})
.on('click',".static",function(e){
e.preventDefault();
var that=this
var xhr=$.get($(this).attr("href"),function(a){
$(that).removeClass('static')
var $loaded=$(a)
var next_section=$($("#section-template").html());
var num_sections=$(".section").length + 1
next_section.addClass(num_sections%2 ? "white" : "black")
next_section.find(".posts").html($loaded.find("#posts").html())
var next_link=$loaded.find(".static")
if(next_link.length){
next_section.find(".static").attr("href",next_link.attr("href"))
} else {
next_section.find(".static").hide()
}
$("#horizontal-scroller").append(next_section); //append to body
$("#horizontal-scroller").width(4000*num_sections); //resize body
$('html, body').stop().animate({
scrollLeft: $(next_section).offset().left
}, 1000);
}) //$.get
}) //click
Here's a live demo of it working. Didn't really bother with making the slides look nice but hopefully you found this helpful.
Of course, everything has to happen on one page, or you can't exactly have the transition. So, either you load everything at run time, or you 'cheat' using AJAX.
alter the in-page javascript to the following:
function bindAnimation(event) {
var $anchor = $(this);
/*
if you want to use one of the easing effects:
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1500,'easeInOutExpo');
*/
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1000);
event.preventDefault();
}
$(function() {
$('ul.nav').on('click','.getNew',getNewSection);
$('ul.nav').on('click','a',bindAnimation);
});
This allows you to add a elements dynamically to the navs, and will attach an event listener to a new element we will use to get new content.
Modify the nav menu so that the last element is something like:
<li class="getNew">New</li>
There. now clicking on that will load the new content.
add this javascript code to your site above the previous javascript code:
window.newSectionBlack = false;
window.SectionID = 4;
function displaySection(data,textStatus, jqXHR) {
$('#section3').after(data.html); //add the new section
$('#'+data.id).addClass(newSectionBlack ? 'black' : 'white');
newSectionBlack = !newSectionBlack; //style it consistently
$('.getNew').before('<li><a href="#'+data.id+'">'+data.name+'</li>'); //attach a link to the new section to the menu
$('body').css({width:4000*SectionID});
$('#'+data.id+' ul.nav').on('click','a',bindAnimation); //bind scripts
$('#'+data.id+' ul.nav').on('click','.getNew',getNewSection);
$('#section1 > ul li:nth-last-child(2) > a').trigger('click'); //go to new
SectionID++;
}
function getNewSection() {
$.ajax({
type: "POST",
url: 'LoadSection.php',
data: {section:SectionID},
success: displaySection,
dataType: 'json'
});
}
This javascript will POST a number corresponding to which section to load to a new file, LoadSection.php, which needs to respond with the HTML of the new section, the ID and name it should be called.
loadSection.php can look like this:
<?php
header('Content-Type: application/json');
$send = array();
switch($_POST['section']) {
default:
$send['html'] = '<div class="section" id="section'.$_POST['section'] .'"><h2>Section ' . $_POST['section'] . '</h2>
<p>
This is a new section loaded via AJAX, cool huh?
</p>
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li class="getNew">New</li>
</ul>
</div>';
$send['id'] = 'section'.$_POST['section'];
$send['name'] = $_POST['section'];
}
echo json_encode($send);
Now, your page can load content dynamically!
Note, the nav bar should probably be restructured to be an absolute element that there's only one of instead of repeated on every page, and there's other stuff you can clean up but that's to be expected if you're taking a codrops example.
EDIT:
tumblr doesn't let you run server-side scripts on their server (makes sense), which are required for the AJAX method described above to work. However, there are a number of options available to you.
1) redirect the tumblr page to a site you control, and use the method described above.
2) use an iframe.
The iframe method could be done directly, which requires you to specify the urls of all the pages in advance (or at least they'll need to follow a predictable pattern), or indirectly using a AJAX script similar to the one above. I will demonstrate loading a direct iframe, I'm sure you can figure out the rest.
window.newSectionBlack = false;
window.newSectionID = 4;
function getNewSection() {
$('#section3').after('<div class="section" id="section'+newSectionID+'"><h2>New Section</h2>
<iframe src="yourtumbrsite.com></iframe>
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li class="getNew">New</li>
</ul>
</div>
'); //add the new section
$('#section'+newSectionID).addClass(newSectionBlack ? 'black' : 'white');
newSectionBlack = !newSectionBlack; //style it consistently
$('.getNew').before('<li><a href="#section'+newSectionID+'">'+newSectionID+</li>'); //attach a link to the new section to the menu
$('body').css({width:4000*newSectionID});
$('#'+data.id+' ul.nav').on('click','a',bindAnimation); //bind scripts
$('#'+data.id+' ul.nav').on('click','.getNew',getNewSection);
$('#section1 > ul li:nth-last-child(2) > a').trigger('click'); //go to new
newSectionID++;
}

Next/Prev buttons onClick scroll to next and previous <td>'s

I'm still learning JavaScript and need some help. I am making next and previous buttons that cause a scroll to the next or previous <td>'s on the page. I'm trying to implement this to the existing structure of a virb site.
the markup looks like this:
div id="next">next</div><div id="prev">prev</div>
<table>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
<tr><td>code that includes img</td></tr>
</table>
Here is the script I'm working with:
jQuery.easing.def = "easeInOutQuad";
$("#next").click(function (){
//$(this).animate(function(){
$('html, body').animate({
scrollLeft: $("td").next.offset().left
}, 600);
//});
});​
​Here is the jsFiddle I'm working on
Try:
scrollLeft: $("td").next().offset().left
The following keeps track of your current item to view. You'll need a similar thig to decrement the index in your 'prev' routine.
You may also need to add a delay or an event cut-off so that multiple clicks during animation don't take the value of currentIdx above or below the range of items you have to show.
var currentIdx = 0;
jQuery.easing.def = "easeInOutQuad";
$("#next").click(function (){
//$(this).animate(function(){
$('html, body').animate({
scrollLeft: $("td").eq(currentIdx).offset().left
}, 600);
currentIdx++;
//});
});

Categories

Resources