How to optimize my loading JQuery function? - javascript

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;
});

Related

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>

How do I make a loop in jQuery so that theres a number added to the end of my divs?

I want the numbers in the div id's and div classes to loop and be from 0 to however many divs I have.. How can I accomplish this? I've tried to put it in a for loop but it doesn't work for some reason..
$("#bokautbildning0").hide();
$(".boka_btn0").click(function(){
$("#bokautbildning0").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
$("#bokautbildning1").hide();
$(".boka_btn1").click(function(){
$("#bokautbildning1").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
$("#bokautbildning2").hide();
$(".boka_btn2").click(function(){
$("#bokautbildning2").slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
Here's the code with the loop I tried:
for ( var i = 0; i < 5; i++ ) {
$("#bokautbildning" + i).hide();
$(".boka_btn" + i).click(function(){
$("#bokautbildning" + i).slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
}
This answer was written for an older version of the question and is no longer correct.
The best solution would be to add a class to all those elements and use that instead of ids to run jQuery on. Let jQuery do the work to iterate over all those elements.
For example, give all elements #bokautbildningn the class .bokautbildning and change your javascript code to this:
$('.bokautbildning').hide();
$('.boka_btn1').click(function(){
$('.bokautbildning').slideToggle();
var scrollToId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(scrollToId).offset().top - 270
}, 500);
return false;
});
The jQuery for this would be pretty straightforward if you made use of data attributes. To wit:
Html example:
<div data-number="1"></div>
<div data-number="2"></div>
<div data-number="3"></div>
<div data-number="4"></div>
<div data-number="5"></div>
jquery:
$("div[data-number]").each(function() {
var number = $(this).data("number");
$(this).html(number);
alert(number);
})
To see it in action:
http://jsfiddle.net/uubxj55r/
You need to use Each and just make sure all items have the same class within each section. There is no need to use the numbering system that you are currently using.
$('.MyDivs').each(function(index){ //Loop through all the elements with class of 'MyDivs'
var thisElement = $(this); //get the current element we're on in the loop
thisElement.find('.bokautbildning').slideToggle(); //Find the element with class 'bokautbildning' within the current element in the loop and slideToggle it
thisElement.find('.boka_btn').click(function() { //Find the element with classs 'boka_btn' within the current element in the loop and add a click listener
//Code for click event happens here
});
}
Here's an example: http://jsfiddle.net/o85tk0s3/

jQuery/Javascript code repetition

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?

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);
});

Localscroll toggle

For many sites (including mine) it would really be useful if we could use jQuery localscroll to send someone to the end of the site, and then when they reach the end, reverse the direction, so the next click would take you back up to the top of the site.
Has anyone done something like this? Any ideas on how to accomplish it (I'm a js newbie).
Well this code may do what you want? DEMO
var bottom = false;
$('body').delegate('span', 'click', function() {
if (bottom === true) {
$("html, body").animate({
scrollTop: '0px'
}, "slow");
bottom = false;
} else {
$("html, body").animate({
scrollTop: $(document).height()
}, "slow");
bottom = true;
}
});

Categories