How to turn these 3 scripts into 1? - javascript

I have a script that does similar things for different id's and i'm pretty much certain this can be done in 1 script rather than 3, any suggestions are welcome.
$("#size-btn-one").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-one").offset().top -100}, 2000);
});
});
$("#size-btn-two").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-two").offset().top -100}, 2000);
});
});
$("#size-btn-three").click(function() {
$('html,body').animate({
scrollTop: $(".scroll-three").top -100}, 2000);
});
});

Combine the selector, you can make an and select by comma separation, like you did with html, body too. And you can extract the name from the element id by different ways, e.g with a simple replace.
$("#size-btn-one, #size-btn-two, #size-btn-three").click(function() {
// getting only the last part of the elements id
var id = $(this).attr("id").replace("size-btn-", "");
$("html, body").animate({
// append the 'id' to the selector class
scrollTop: $(".scroll-" + id).offset().top -100}, 2000);
});
});

$("#size-btn-one, #size-btn-two, #size-btn-three").click(function(){
var id = $(this).attr("id");
var number = id.substring(id.lastIndexOf("-"));
$('html,body').animate({
scrollTop: $(".scroll-"+ number).offset().top -100}, 2000);
});
});

As an alternative, I'd pair up the btn and the scroll- using data- attributes and not use id= for this.
<a href='#' data-link='1'>one</a>
<a href='#' data-link='2'>one</a>
<a href='#' data-link='xyz'>one</a>
<div data-link='1'>content 1</div>
<div data-link='2'>content 2</div>
<div data-link='xyz'>content 3</div>
This also means you can use semantic definitions, rather than just numbers (though you could with IDs as well ofc).
Then:
$("a[data-link]").click(function() {
var link = $(this).data("link");
var div = $("div[data-link=" + link + "]");
$('html,body').animate({
scrollTop: div.offset().top - 100}, 2000);
});
});
Normally, you'd also add a class, but left off to show the concept of pairing via data attributes.

$("#size-btn-one, #size-btn-two, #size-btn-three").on("click",function(){
var idLastPart = $(this).attr('id');
idLastPart = idLastPart.match(/one|two|three/)[0];
$('.scroll-'+idLastPart).animate({
//your animation
},300);
});

Related

Javascript array click

I'm trying to avoid having the same lines of Javascript for the same purpose.
I have 3 sections:
<div class="specs"></div>
<div class="description"></div>
<div class="comments"></div>
And these 3 links:
Produkt beskrivelse
Produkt specs
</i>Kommentarer
And this javascript which, on click scrolls to the section
$(".facebook").on('click', function () {
$('html, body').animate({
scrollTop: $(".comments").offset().top - 200
}, 1000);
});
$(".readMore.desc").on('click', function () {
$('html, body').animate({
scrollTop: $(".description").offset().top - 200
}, 1000);
});
$(".readMore.spec").on('click', function () {
$('html, body').animate({
scrollTop: $(".specs").offset().top - 200
}, 1000);
});
These 3 pieces of javascript code is annoying because it does the exact same thing.
A live example can be seen here a live example. You'll see the 3 buttons on the right of the product image.
I don't know if a solution could be to add an array of some sort?
One way of handling this is giving each link a data- property that describes where the link should scroll to. You can use .data() to access these properties.
$(".readMore").on('click', function() {
// Get the selector of where to scroll to
var selector = $(this).data('selector');
$('html, body').animate({
scrollTop: $(selector).offset().top - 200
}, 1000);
});
html, body {
height: 100%;
}
div {
height: 100%;
margin-top: 20px;
border: solid 1px #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Produkt beskrivelse
Produkt specs
Kommentarer
<div class="specs">
Specs
</div>
<div class="description">
Description
</div>
<div class="comments">
Comments
</div>
Common classes (which you have) and data attributes will save you here.
Produkt beskrivelse
Produkt specs
</i>Kommentarer
And now, one handler to rule them all:
$(".readMore").on('click', function () {
var dest = $(this).data("dest");
$('html, body').animate({
scrollTop: $(dest).offset().top - 200
}, 1000);
});
//extraced the common parts
function scrollToTop ( elementSelector ) {
$('html, body').animate({
scrollTop: $(elementSelector).offset().top - 200
}, 1000);
}
$(".facebook").on('click', function () {
scrollToTop('.comments');
});
$(".readMore.desc").on('click', function () {
scrollToTop('.description');
});
$(".readMore.spec").on('click', function () {
scrollToTop('.specs');
});
Use a helper function instead of copy-pasting your code
function foo(target, element) {
target.on('click', function () {
$('html, body').animate({
scrollTop: element.offset().top - 200
}, 1000);
});
}
foo($(".facebook"), $(".comments"));
foo($(".readMore.desc"), $(".description"));
foo($(".readMore.spec"), $(".specs"));
Probably better you just read the class on the object, split it to get the value you want. As such:
$('.readMore').on('click', function() {
var classes = $(this).attr('class');
var cursor = class.split(' ')[1];
if(cursor == 'facebook') {
...
}else if(cursor == 'desc') {
...
} else if(cursor == 'spec') {
...
}
});
First you'll need to map which dom is effecting which. you could have solved this by using some kind of class name convention. I'll assume you can't decide on the class names. So let's create a map/object/hash
var map = {
spec: "specs",
desc: "description",
facebook: "comments,
}
Now let's just iterate the map and add the functionality
Object.keys(map).forEach(function(key) {
var value = map[key];
$(".readMore." + key).on('click', function () {
$('html, body').animate({
scrollTop: $("." + value).offset().top - 200
}, 1000);
});
})
And now you are a happy coder.
If you've learned closures, I prefer those to make re-usable events more readable...
I have a jsFiddle for this here
// use a closure to make your event's callback,
// with the target as a parameter
function makeClickFn(target) {
return function() {
$('html, body').animate({
scrollTop: $(target).offset().top - 200
}, 1000);
};
}
var clickFn;
// facebook comments
clickFn = makeClickFn('.comments');
$(".facebook").on('click', clickFn);
// readmore description
clickFn = makeClickFn('.description');
$(".readMore.desc").on('click', clickFn);
// readmore specs
clickFn = makeClickFn('.specs');
$(".readMore.spec").on('click', clickFn);

How to simplify jQuery code , plugin, scroll to the block

How to simplify jQuery code.
If I have 1 page with several different blocks.
I need to duplicate this code multiple times to use different elements?
How to write 1 code for multiple blocks ?
$('.go_to').click( function(){
var scroll_el = $(this).attr('href');
if ($(scroll_el).length != 0) {
$('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500);
}
return false;
});
<a class="go_to" href="#elm">button</a> или <a class="go_to" href=".elm">block-scroll</a>
$('.go_to-1').click( function(){
var scroll_el = $(this).attr('href');
if ($(scroll_el).length != 0) {
$('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500);
}
return false;
});
<a class="go_to-1" href="#elm">button</a> или <a class="go_to-1" href=".elm">block-scroll</a>
$('.go_to-2').click( function(){
var scroll_el = $(this).attr('href');
if ($(scroll_el).length != 0) {
$('html, body').animate({ scrollTop: $(scroll_el).offset().top }, 500);
}
return false;
});
<a class="go_to-2" href="#elm">button</a> или <a class="go_to-2" href=".elm">block-scroll</a>
Given your example, the simplest way is to select multiple elements with jquery using a comma separated list, and define the click handler all of them at once:
$('.go_to, .go_to-1, .go_to-2').click( function(){
//on click code
});
I am assuming you need different classes for the anchors, but if not, you could just give them all the same class (for example class="go_to") and use
$('.go_to').click( function(){
//on click code
});

HTML using onclick input to run javascript code

I am currently trying to implement a menu with many clickable buttons - appetizers, soups, etc. By using parameters, I can send the type of food to my JavaScript.
These are the buttons.
http://puu.sh/kugEs/5048221343.jpg
This is the code when I click on appetizers.
function scroll(type) {
var test = "('#" + type + "')";
alert(test); //('#appetizers')
$("html, body").animate({ scrollTop: $test.offset().top-150 }, 600); //this doesnt work
$("html, body").animate({ scrollTop: $('#appetizers').offset().top-150 }, 600); //this works
}
Of course I want to make it so that I don't have to manually use the working line. I want to use the one that doesn't work that it can be applied to all buttons running the same function with only different parameters.
How can I use the var test in order to run the line that doesn't work?
You should use $ and take care about your quotes::
var $test = $('#' + type); // Now it's a jQuery Object
In your example:
function scroll(type) {
var $test = $('#' + type);
$("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}
You should define $test as an object, instead of a string.
function scroll(type) {
var test = $('#' + type);
alert($test.attr("id")); // appetizers
$("html, body").animate({ scrollTop: $test.offset().top-150 }, 600);
}
Try it with this code. It should work.
function scroll(type) {
var test = "('#" + type + "')";
alert(test); //('#appetizers')
$("html, body").animate({ scrollTop: $('#'+type).offset().top-150 }, 600);
}

Pass dynamic id value jquery div jump to function

I am stuck at jquery div jump to problem. The problem is that i am creating dynamic and dynamic div also say <div id="1_1_div"></div> i am using following jquery function to scroll to a particular div
<script>
$(document).ready(function (){
$("#click").click(function (){
alert ("test");
//$(this).animate(function(){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 1000);
//});
});
});
</script>
My question is how to pass dynamic id to $("") Any help would be highly appreciated.
$(document).ready(function (){
$(".click").click(function (){
alert ("test");
var divID = '#' + $(this).attr('id') + '_div';
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 1000);
});
});
And add <a class="click" ...
String Concatenation:
$("#" + this.id + "_div").offset().top
Note that there is no need to create unique IDs, DOM duo to having tree-like structure provides many different methods for traversing and selecting the target elements.
Since you are generating the elements dynamically you should also delegate the events, you can add classes to your elements and use the on method:
$('#aStaticParentElement').on('click', '.anchors', function() {
// TODO:
// select the target element either by traversing
// or by using an identifier
});
Visualize it here
First, since you have multiple links, use a class to group them:
HTML
Click me 1_1
Click me 1_2
Click me 1_3
jQuery
$(document).on('click', '.click', function (e) {
var theID = $(this).attr('id');
$('html, body').animate({
scrollTop: $('#' + theID + '_div').offset().top
}, 1000);
return false;
});
I did this with the slight assumption you were dynamically creating these links (hence the delegation). If they are static and won't change during page load, you can use $('.click').click(function()... instead of $(document).on('click', '.click', function()...
User this line
$("#" + $(this).attr("id") + "_div").offset().top
...

Anchor Onclick Division Highlight

I have made a simple webpage with lots of division. So to navigate direct to a division I have put a anchor on top like this :
First<br/>
Second<br/>
Third
And for smooth scrolling I have used javascript:
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});
Now I want to add effect to the selected division. So when user click on an anchor, the page smoothly scrolls to the division and the selected division is highlighted for a second. Just like when we get any news in Stack Overflow inbox, and we click on it; the page lodes and the news item is highlighted for a short duration.
I want to do that thing to my page. Cause I'm having more then 18 divisions and they are all same.So it is necessary to differentiate the selected division.
Here is the example Fiddle : Fiddle For the Code
Any help would be appreciated. Thanks in advance.
In Your code $('html, body') returns 2 elements so animation will fire twice. If you include jquery.ui You will be able to do this:
$('a').click(function(){
var selector = $(this).attr('href');
$('html').animate({
scrollTop: $(selector).offset().top
}, 500,'',function(){
$(selector).effect("highlight", {}, 1000);
});
return false;
});
JsFiddle
This use opacity like example:
$('a').click(function(){
var el = $(this).attr('href');
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500, function(){
$(el).animate({'opacity':0.5},200, function(){ $(el).animate({'opacity':1}, 200)} );
});
return false;
});

Categories

Resources