jQuery/Javascript code repetition - javascript

I am trying to use the scrollTop function for my program, but I am finding that I am writing a lot of repetitive code.
This is an example:
<div id="table_contents >
<ul>
<li id="one"> title One </li>
<li id="two"> title Two </li>
</ul>
</div>
<div id="content">
<p id="target_one"> I am content one </p>
<p id="target_two"> I am content two </p>
</div>
If i was to click on 'title One' I want to scroll to 'I am content one'
Likewise for title two and content two.
This is easy enough to do with jQuery/JS
$("#one").click(function() {
$('html, body').animate({
scrollTop: $("#target_one").offset().top -20
}, 800);
});
But say for example my table of contents has 15 elements in it, and I want to make each clickable to scroll to its content. For this I would have to repeat the above code 15 times for each element.
Is there a better way than that?

Just change your script to :
Method 1
$("#table_contents").on("click","li",function() {
$('html, body').animate({
scrollTop: $("#target_"+$(this).prop('id')).offset().top -20
}, 800);
});
In this method, the id of the clicked element will be appended to "target_", to locate the "target id". This method will work even for the dynamically added li elements.
Method 2 :
Without ids [but same order]:
$("#table_contents").on("click","li",function() {
$('html, body').animate({
scrollTop: $("#content p").eq($(this).index()).offset().top -20
}, 800);
});
in this method, the index of the element li is mapped to the index of the p elements to locate the scroll location.
And done!!
http://jsfiddle.net/bmL0o9ez/
http://jsfiddle.net/bmL0o9ez/2/

LIVE FIDDLE DEMO
$("#table_contents ul li").click(function () {
var theIdAttr = $(this).attr("id");
$("html, body").animate({
scrollTop: $("#target_" + theIdAttr).offset().top -20
});
});

You can use a more generic selector for type sort of thing where each element requires identical behavior.
$("#table_contents li").click(function() {
var liElement = $(this);
$('html, body').animate({
scrollTop: $("#target_" + liElement.attr('id')).offset().top -20
}, 800);
});

You can build the id of the paragraph dynamically based on the id of the li.
HTML
title One
title Two
<div id="content">
<p id="target_one"> I am content one </p>
<p id="target_two"> I am content two </p>
</div>
Javascript:
$("#table_contents li").click(function() {
$('html, body').animate({
scrollTop: $('#target_' + $(this).attr('id')).offset().top -20
}, 800);
});

Here's a solution that doesn't rely on using IDs at all, but instead uses jQuery's index() function:
$("#table_contents li").click(function () {
$('html, body').animate({
scrollTop: $("p").eq($(this).index()).offset().top - 20
}, 800);
});
jsFiddle example

Make it generic, like:
$("#table_contents ul li").click(function() {
$('html, body').animate({
scrollTop: $('#target_'+ $(this).attr("id")).getId.offset().top -20
}, 800);
});
if you keep the content in order you could even go ultra generic, like:
$("#table_contents ul li").click(function() {
var index = $(this).index();
$('html, body').animate({
scrollTop: $('#content:nth-child('+index+')').getId.offset().top -20
}, 800);
});
Not tested, but it should give you an idea
cheer mate

I do
$("#content p").each(function() {
var heights = [];
heights.push($(this).offset().top);
});
Then do
heights[your_target_as_index];
Done?

Related

How to optimize my loading JQuery function?

I have sidebar which contains a lot of titles. I don't want to write for all of them a function. Here is a code for one :
$("#menu_documentations").click(function () {
$("#sites").load("documentations/documentations_doc.php");
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
The sidebar's id always look like "#menu_xyz" and the loading php using the same "xyz_doc.php".
How can I avoid to write one by one ?!
use a class and a data attribute for the url
html:
<a class="load-ajax" href="#" data-url="coustom-page-name.html">Link</a>
or
<a class="load-ajax" href="coustom-page-name.html">Link</a>
js:
$(".load-ajax").click(function () {
var url = $(this).attr('data-url');//$(this).attr('href');
$("#sites").load(url);
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
The below would work (same as madalin's except I would just use the data attribute itself to target the elements rather than adding another class):
HTML:
<button data-get-page="documentations/documentations_doc.php">click me </button>
JS:
$(document).on('click','[data-get-page]',function() {
var $this=$(this);
var url=$this.data('get-page');
$("#sites").load(url);
$("html, body").animate({
scrollTop: 0
}, "slow");
return false;
});

How to move the page up each time to a div

I am creating a form where i have many child forms to submit,so i have used a jQuery functionality where each submit a msg will show at the top of the page ,now what i want,on each submit the page will scroll up to the div where that jQuery is calling .Here is my code
var url = "<%=addPersonalDetailsURL%>";
var type = "addPersonalDetails";
if(!($('#<portlet:namespace/>address1').val()=='' || $('#country').val()=='None' ||$('#<portlet:namespace/>primaryPhone').val()=='')){
jQuery.getJSON(url+"&address1="+address1+"&address2="+address2+"&country="+country+"&state="+state+"&city="+city+"&zip="+zip+"&skypeId="+skypeId+"&twitter="+twitter+"&primaryPhone="+primaryPhone+"&secondaryPhone="+secondaryPhone+"&type="+type, function(data) {
$('html, body').animate({
scrollTop: $(".success").offset().top
}, 800);
for(var z=0; z<data.applicationArray.length;z++){
applicationArray = data.applicationArray[z].split("$$##$$##");
address1 = applicationArray[0];
address2 = applicationArray[1];
city = applicationArray[2];
primaryPhone = applicationArray[3];
}
jQuery.getJSON is giving some result where on the basis i have to use that functionality.So can you tell how i should modify your solution
You should need to get your element's top position in the page and move the scroll to that position. Something like the code below:
jQuery(window).scrollTop(jQuery(".success").offset().top);
Note that the code above will move to the first .success position. If you have to reference a specific one, add the index in the selector, for example:
jQuery(window).scrollTop(jQuery(".success:eq(1)").offset().top);
You can do that with this function:
$("button").click(function () {
$('html, body').animate({
scrollTop: $(".whichElement").offset().top
}, 800);
});
Explanation:
If the button is clicked, we scroll the page to the element with class
whichElement and the duration of the scroll is 800ms.
Example:
$(".first-hey").click(function () {
$('html, body').animate({
scrollTop: $(".second-hey").offset().top
}, 800);
});
$(".second-hey").click(function () {
$('html, body').animate({
scrollTop: $(".third-hey").offset().top
}, 800);
});
$(".third-hey").click(function () {
$('html, body').animate({
scrollTop: $(".first-hey").offset().top
}, 800);
});
.divide {
height: 1300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="first-hey">First hey</button>
<div class="divide"></div>
<button class="second-hey">Second hey</button>
<div class="divide"></div>
<button class="third-hey">Third hey</button>

Scroll to page depending on button that is clicked

Can anyone explain to me how I can use the jquery scroll-to to make the buttons on the yellow menu scroll to their corresponding sections (i.e distribution to the pink block)
This is my code: http://jsfiddle.net/VXkW5/5/
I think its something like this:
$(".nav").click(function () {
$('html, body').animate({
scrollTop: $(".section").offset().top + $(".section").height()
}, 500);
});
But I dont know how to relate it to it's relevant section based on the link that was clicked.
Working Demo
First of all, ID need to be unique in the page. I see both as well as uses same ID
so i have made change & Just add the corresponding div id to the href tag, it will take to that particular div on click
posting
distribution
applicantions
In terms of jQuery:
$(".nav").click(function (e) {
e.preventDefault();
var divId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(divId).offset().top;
}, 500);
});
You could have a link like
Click to jump to section 1
And a section like
<div id="section1">
<p>Section 1 content</p>
</div>
And handle the scroll to like so
<script type="text/javascript">
$(".nav").click(function (event) {
event.stopPropagation();
var theHref = $(this).attr('href');
$('html, body').animate({
scrollTop: $(theHref).offset().top + $(".section").height()
}, 500);
});
</script>

JQuery rolling - stop previous & generalize

i have code like this:
JavaScript
$( document ).ready(function() {
$("a.link1").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link1").offset().top
}, 2000);
//});
});
$("a.link2").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link2").offset().top
}, 2000);
//});
});
$("a.link3").click(function (){
//$(this).stop().preventDefault().animate(function(){
$('html, body').animate({
scrollTop: $("#link3").offset().top
}, 2000);
//});
});
});
Body of HTML:
<div id="menu">
LINK 1
LINK 2
LINK 3
</div>
<div id="content">
<a name="link1" id="link1"></a>
<!--some text-->
<a name="link2" id="link2"></a>
<!--some text-->
<a name="link3" id="link3"></a>
<!--some text-->
</div>
Please help me with this:
Stop doesn't seem to work the way I wanted. I want to somehow stop previous rolling when another link is activated.
Is there any way of generalization of the jQuery part. I have more than 3 menu links and I don't want to make a special function for each.
Thank you very much for your help.
Gomi
You can generalize by extracting the click callbacks to a common function:
var linkClickCallback = function(selector){
$('html, body').stop().animate({
scrollTop: $(selector).offset().top
}, 2000);
}
$( document ).ready(function() {
$("a.link1").click(linkClickCallback.bind(null, '#link1'));
$("a.link2").click(linkClickCallback.bind(null, '#link2'));
$("a.link3").click(linkClickCallback.bind(null, '#link3'));
});
Note that in the linkClickCallback i also wrote the proper use of stop() method.
EDIT:
This will work for all items in menu:
$( document ).ready(function() {
$("#menu a").click(function(e){
e.preventDefault();
linkClickCallback('#' + this.className);
});
});
with the same linkClickCallback function.
Yeah just generalise a function like this and then inside the function, look for the caller (this):
$("#menu a").click(function(e){
var t = $(this)
$('html, body').animate({
scrollTop: t.offset().top
}, 2000);
});

ScrollTop to element - 20px

I'm trying to make a scrollTop to my div element, but not exactly where it is. I want
to go 20px before my div element. I think i can explain better showing my code for you:
HTML:
<div id="arrow-down">Click here and go to content!</div>
<div id="content">The content is here!</div>
JQuery:
I already have a code that is working fine, but i want to make it diference.
$(document).ready(function() {
$('#arrow-down').click(function() {
$('html, body').animate({
scrollTop: $("#content").offset().top
}, 800);
});
});
This code takes me to the div#content, but i want to go 20px from the top of this!
Something like that:
$(document).ready(function() {
$('#arrow-down').click(function() {
$('html, body').animate({
scrollTop: $("#content" - 20px).offset().top
}, 800);
});
});
Well, i dont know if its look confused... I hope u guys can help me!
You can do this:
$('html, body').animate({
scrollTop: $("#content").offset().top - 20
}, 800);
$(document).ready(function() {
$('#arrow-down').click(function() {
$('body').animate({
scrollTop: $("#content").offset().top-20
}, 800);
});
});
try this

Categories