jQuery - Create a function and call it - javascript

How can I create a function in jQuery and call it?
This doesn't seems to be correct:
var scrollLink = function() {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
};
$('.js-ask').click(function(e) {
e.preventDefault();
$('[href="' + this.dataset.target + '"]').tab('show');
reportReadMessages();
});
$(".js-scroll").click(function(e, scrollLink) {
e.preventDefault();
scrollLink();
});

You aren't passing what is this in the scrollLink(). It is a function with empty parameters, when it doesn't understand what this is. So please change it to:
$('.js-ask').click(function(e) {
e.preventDefault();
$('[href="' + this.dataset.target + '"]').tab('show');
reportReadMessages();
});
$(".js-scroll").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
});
You are not passing the scrollLink in the right way. That's why it didn't work.
Or you can extend the function this way:
$.fn.scrollLink = function() {
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top-20
}, 300);
};
And you can call on the elements like:
$(this).scrollLink();
$(selector).scrollLink();
See How to add a function to jQuery? for more information.

Related

jQuery combine 2 scripts to achieve smooth scrolling to anchor

I have the following jquery function which shows / hides content depending on the div that is selected...
jQuery(document).ready(function() {
jQuery('.showSingle').on('click', function () {
jQuery(this).addClass('selected').siblings().removeClass('selected');
jQuery('.targetDiv').hide();
var selector = '#div' + jQuery(this).data('target');
jQuery(selector).show();
location.hash = selector;
});
});
http://jsfiddle.net/W4Km8/7944/
I also have the following script taken from http://1stwebmagazine.com/jquery-scroll-to-anchor-point
$(document).ready(function(){
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
I am trying to combine the 2 so that instead of jumping to the anchor it scrolls to it. Do I need to combine them or can they be made to work separate?
Looks like you can combine them easily enough, I've made it work with this jsfiddle: http://jsfiddle.net/9soxbhpj/
var target = jQuery(selector);
target.show()
$('html, body').stop().animate({
'scrollTop': target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = selector;
});
You can add the scroll action in the same click call.
See the js:
jQuery(document).ready(function() {
jQuery('.showSingle').on('click', function () {
var _el = jQuery(this),
_target = jQuery('#div' + _el.data('target')),
_targetDiv = jQuery('.targetDiv');
_el.addClass('selected').siblings().removeClass('selected');
_targetDiv.hide();
_target.show();
// Scroll to object
$('html, body').animate({
scrollTop: _target.offset().top
}, 800);
});
});
Here is a working example.

Toggle div after arriving from anchor link

My goal is to create anchor link with smooth scrolling to its destination and after it reaches it, toggle class to open accordion.
I have a hard time achieving a working result. Scroll code is here:
var $root = $('html, body');
$('.calendar a').click(function() {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
I have no hash in my url.
How to include toggle in this scroll code?
Thanks!
There is an "completed" function callback you can stick at the end of the animation, like so:
var $root = $('html, body');
$('.calendar a').click(function() {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500, function() {
//DO YOUR TOGGLE HERE
$('#target').toggleClass('myClass')
});
return false;
});
You can simply wait for the animate to complete using a jQuery promise and always. This works better than the animation callbacks (which do not fire if you are already at the final position)
JSFiddle http://jsfiddle.net/fb6yuf9k/1/
e.g.
var $root = $('html, body');
$('.calendar a').click(function () {
var $target = $($.attr(this, 'href'));
$root.animate({
scrollTop: $target.offset().top
}, 500).promise().always(function(){
$target.toggle();
});
return false;
});
For the specific website provided in comment, you want to toggle the element with toggle-content beneath the target element:
e.g.
var $root = $('html, body');
$('.calendar a').click(function () {
var $target = $($.attr(this, 'href'));
$root.animate({
scrollTop: $target.offset().top
}, 500).promise().always(function(){
$target.find('.toggle-content').toggle(); // or toggleClass etc
});
return false;
});

Merging multiple jquery functions into one

I'm very new to jquery. I can seem to get stuff to work but the code is hideous in terms of length and I find myself repeating...
Can anyone assist with the shortest way to write the following... I've tried various things with it but it messes up the way in which the code works... this is basically a series of panels and buttons in a step by step process... when one button is clicked the next fades in and auto scrolls to a specific height.
<script>
$(".steptwobtn").on( "click", function(e){
$(".steptwo").fadeIn().css("display","block");
$(".costs").fadeIn().css("display","block");
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
});
$(".stepthreebtn").on( "click", function(e){
$(".stepthree").fadeIn().css("display","block");
$(".size-costs span").css("visibility","visible");
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
});
$(".stepfourbtn").on( "click", function(e){
$(".stepfour").fadeIn().css("display","block");
$(".worktop-costs span").css("visibility","visible");
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
});
$(".stepfivebtn").on( "click", function(e){
$(".stepfive").fadeIn().css("display","block");
$(".appliances-costs span").css("visibility","visible");
$(".install-costs span").css("visibility","visible");
$(".total-costs span").css("visibility","visible");
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
});
</script>
I'm thinking there must be a neater way of writing this and not having to repeat the scroll function each time?
Many thanks in advance. I'm tearing my hair out!
G
You can move the scroll logic out to a separate function and then call it from within each jQuery click handler:
<script>
$(".steptwobtn").on( "click", function(e){
$(".steptwo").fadeIn().css("display","block");
$(".costs").fadeIn().css("display","block");
scroll(this);
});
$(".stepthreebtn").on( "click", function(e){
$(".stepthree").fadeIn().css("display","block");
$(".size-costs span").css("visibility","visible");
scroll(this);
});
$(".stepfourbtn").on( "click", function(e){
$(".stepfour").fadeIn().css("display","block");
$(".worktop-costs span").css("visibility","visible");
scroll(this);
});
$(".stepfivebtn").on( "click", function(e){
$(".stepfive").fadeIn().css("display","block");
$(".appliances-costs span").css("visibility","visible");
$(".install-costs span").css("visibility","visible");
$(".total-costs span").css("visibility","visible");
scroll(this);
});
function scroll(btn) {
var target = $( $(btn).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
}
</script>
Or, if you'd like to merge it all together you could do the following. The problem is that each function is doing something subtly different. For the following to work, you'd need to add an attribute to each btn, 'data-step-number', and change the css class of each button just to be 'stepbtn':
<script>
$(".stepbtn").click(function(e) {
var step = $(this).attr('data-step-number');
$(".step" + step).fadeIn().css("display","block");
switch (step) {
case 2:
$(".costs").fadeIn().css("display","block");
break;
case 3:
$(".size-costs span").css("visibility","visible");
break;
case 4:
$(".worktop-costs span").css("visibility","visible");
break;
case 5:
$(".appliances-costs span").css("visibility","visible");
$(".install-costs span").css("visibility","visible");
$(".total-costs span").css("visibility","visible");
break;
}
var target = $( $(this).attr('href') );
if( target.length ) {
event.preventDefault();
$('html, body').animate({
scrollTop: (target.offset().top)-155
}, 1000);
}
});
</script>

SyntaxError: Missing ) in a Simple Scrolltop

I have two divs with anchors inside (one with a class of 'renter', the other with a class of 'owner'). When clicked, the page should scroll to elements '#pageInclude119' and '#pageBContent120' respectively. However, I want them to go to a separate page if Javascript isn't work, so that's why they're linked. Here's the HTML:
<div class="button renter">i’m a renter</div>
<div class="button owner">I’m an owner/investor</div>
and here's my Javascript (the preventDefault is to keep the link from going to another page, while the animate is supposed to scroll to an element in the same page):
$( document ).ready(
$('.renter a').on('click', function(){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageInclude119").offset().top
}, 1000);
});
$('.owner a').on('click', function(){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageBContent120").offset().top
}, 1000);
});
);
For some reason, this script returns this error, and doesn't work:
"SyntaxError: missing ) after argument list"
What's going wrong?
Instead of
$(
// Code here
);
Use this
$(function() {
// Code here
});
See jQuery docs.
Few errors, missing function() {} and event parameter in the on click statements:
$( document ).ready(function() {
$('.renter a').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageInclude119").offset().top
}, 1000);
});
$('.owner a').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageBContent120").offset().top
}, 1000);
});
});
In the $( document ).ready you forgot to add a function:
$( document ).ready( function() {
...
});
You got the syntax a bit wrong. The outermost block should be:
$( document ).ready(function() {
//.....
//......
});
or you can use the shorthand:
$(function() {
//.....
//......
});
Here is the updated/working code.
$( document ).ready(function() {
$('.renter a').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageInclude119").offset().top
}, 1000);
});
$('.owner a').on('click', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $("#pageBContent120").offset().top
}, 1000);
});
});

jQuery run onclick function only once

How can I execute this function only one time?
I tried .one but it doesn't work
$('a.inspire-tag').on('click',function () {
$('html, body').animate({
scrollTop: $(".button-inspire").offset().top
}, 400);
});
If you want to do is just click once to enable
Try this:
$('a.inspire-tag').on('click',function () {
$('html, body').animate({
scrollTop: $(".button-inspire").offset().top
}, 400);
$('a.inspire-tag').off('click');
});
$('a.inspire-tag').on('click',doThis);
function doThis () {
$('html, body').animate({
scrollTop: $(".button-inspire").offset().top
}, 400);
//you can off all on callback function
$('a.inspire-tag').off('click',doThis);
}
Use .off(), with name spaced event names
$('a.inspire-tag').on('click.myevent', function () {
if (...)
// remove current event handler
$(this).off('click.myevent')
});
var oneTime = true;
$('a.inspire-tag').on('click',function () {
if(oneTime) {
$('html, body').animate({
scrollTop: $(".button-inspire").offset().top
}, 400);
oneTime = false;
}
});
var inspiretag = $('a.inspire-tag');
inspiretag.on('click',function () {
$('html, body').animate({
scrollTop: $(".button-inspire").offset().top
}, 400);
inspiretag.off('click');
});
http://api.jquery.com/off/

Categories

Resources