Link with hashtag - javascript

I need something link this
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top-55
}, 1000);
return false;
}
}
});
});
But it works only for that link offer. I want that this code works for this link for example offer2

I think your jquery selector is wrong.
See
http://jsfiddle.net/9shvmhwh/5/
$(function() {
$("a[href*='#']:not([href='#'])").click(function(event) {
location = $(this).attr('href');
event.stopPropgation();
return true;
});
});

Related

the hash link not matched with nav menu

when I click on navbar item the hash link scroll event not matched with the correct nav menu item
I tried to change the 'scrollto' variable up or down but the problem still exists
below is the code :
// Smooth scroll for the menu and links with .scrollto classes
var scrolltoOffset = $('#header').outerHeight() - 21;
var clicked = false;
$('.nav-menu a, #mobile-nav a, .scrollto').on('click', function(e) {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
debugger;
if (target.length) {
e.preventDefault();
var scrollto = target.offset().top - scrolltoOffset;
if ($(this).attr("href") == '#header') {
scrollto = 0;
}
$('html, body').animate({
scrollTop: scrollto
}, 1500, 'easeInOutExpo');
if ($(this).parents('.nav-menu').length) {
$('.nav-menu .menu-active').removeClass('menu-active');
$(this).closest('li').addClass('menu-active');
}
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
$('#mobile-body-overly').fadeOut();
}
return false;
}
}
});
this is the live site innovators.com
Easy fix. You are not scrolling enough.
Just scroll two pixels less: -21 => -23
// Smooth scroll for the menu and links with .scrollto classes
var scrolltoOffset = $('#header').outerHeight() - 23;
var clicked = false;
$('.nav-menu a, #mobile-nav a, .scrollto').on('click', function(e) {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
debugger;
if (target.length) {
e.preventDefault();
var scrollto = target.offset().top - scrolltoOffset;
if ($(this).attr("href") == '#header') {
scrollto = 0;
}
$('html, body').animate({
scrollTop: scrollto
}, 1500, 'easeInOutExpo');
if ($(this).parents('.nav-menu').length) {
$('.nav-menu .menu-active').removeClass('menu-active');
$(this).closest('li').addClass('menu-active');
}
if ($('body').hasClass('mobile-nav-active')) {
$('body').removeClass('mobile-nav-active');
$('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
$('#mobile-body-overly').fadeOut();
}
return false;
}
}
});

Anchor Transition conflicting with Bootstrap click function for Tabs

I'm trying to use a bootstrap tab click function but I'm having trouble with also using the animation for an anchor tag I got from stackoverflow. It seems like the on click function is messing up the on click function for the tab Is there a way around this?
<div id="tab1">
<ul class="tab1-titles">
<li class="active">
Tab1
</li>
<li>
Tab2
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="1a">
<ul>
<li>list-item-1</li>
<li>list-item-2</li>
</ul>
</div>
<div class="tab-pane active" id="2a">
<ul>
<li>list-item-1</li>
<li>list-item-2</li>
</ul>
</div>
</div>
</div>
Javascript
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
instead of adding new click event handler, just use built-in tab change event like below
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
var hash = $(e.target).attr("href");
//your code goes here
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(hash);
target = target.length ? target : $('[name=' + hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
}
}
});
I had a co-worker look at it for me and he suggest of just adding a class to the anchor tag within this script. So I did and it works perfectly! I just had to make a more direct call for this function to work. He even added a offset scrolltop just in case you have a fixed header into the equation.
$('a[href^="#"].anchortargets:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: parseInt(target.offset().top) - 140 + 'px'
}, 500);
return false;
}
}
});

javascript module with JQuery causing module functions to be undefined

I'm trying to make a module called ScrollToAnchor that has a function called goToTarget that I will be able to call like ScrollToAnchor.goToTarget(target);
However it says that
ScrollToAnchor.goToTarget is not a function
I think ScrollToAnchor is of type jQuery how I have it because of the $. Here is the code:
var ScrollToAnchor = $(function() {
var headerHeight = 70;
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
if (goToTarget(this.hash))
return false;
}
});
/*$('input[data-target]').click(function() {
if (gotoTarget($(this).data("target")))
return false;
})*/
var goToTarget = function(targetName) {
var target = $(targetName);
target = target.length ? target : $('[name="' + targetName.slice(1) + '"]');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerHeight
}, 1000);
return true;
}
return false;
}
return {
goToTarget: goToTarget
}
});
What am I doing wrong? If i remove the $ from var ScrollToAnchor = $(function () { then the jQuery inside ScrollToAnchor doesn't work.
But if I leave the $ there then it thinks ScrollToAnchor is type jQuery and ScrollToAnchor.goToTarget is not a function.
The $(function() {...}) is a short hand of $( document ).ready( handler ).
So the result of $(function() {...}) is a jQuery result set containing the document as element.
You are looking for event delegation:
$(document).on('click', 'a[href*="#"]:not([href="#"])', function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
if (goToTarget(this.hash))
return false;
}
});
This will ensure that the click event will be use for all a element no matter when they have been added to the DOM and allows your to make your goToTarget available in the global scope in an easy way. Your final code will then look this way:
var ScrollToAnchor = (function() {
var headerHeight = 70;
// event handler with delegation
$(document).on('click', 'a[href*="#"]:not([href="#"])', function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
if (goToTarget(this.hash))
return false;
}
});
function goToTarget(targetName) {
var target = $(targetName);
target = target.length ? target : $('[name="' + targetName.slice(1) + '"]');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerHeight
}, 1000);
return true;
}
return false;
}
return {
goToTarget: goToTarget
}
}());
Using event delegation there is no need to wrap you whole code into a $(function() {...}) and your ScrollToAnchor is public available.
Turn ScrollToAnchor into a normal function. This function will be in the global scope:
window.ScrollToAnchorFactory = function () {
var headerHeight = 70;
$('a[href*="#"]:not([href="#"])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
if (goToTarget(this.hash))
return false;
}
});
/*$('input[data-target]').click(function() {
if (gotoTarget($(this).data("target")))
return false;
})*/
var goToTarget = function (targetName) {
var target = $(targetName);
target = target.length ? target : $('[name="' + targetName.slice(1) + '"]');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerHeight
}, 1000);
return true;
}
return false;
}
return {
goToTarget: goToTarget
}
};
You could also use a module.export instead of putting this in the global scope, if you'd like to create a commonJS module out of this code. That would allow you to require() it into other files (using Browserify to compile).
If you do decide to just keep ScrollToAnchorFactory in the global scope, wherever you need to use scrollToAnchor.goToTarget (in the same file or a different one)...
$(function() {
var scrollToAnchor = window.ScrollToAnchorFactory();
// you can now use scrollToAnchor.goToTarget(target)
});
You'll want jQuery's DOM ready function wrapped around this part, so that ScrollToAnchorFactory doesn't try to init before your anchors are fully formed in the DOM.

Understand the code of the smooth scroll script

I'm learning jquery and found a script for smooth scrolling on click, which works perfect, but I don't understand it and I want to understand the code and why does what it does:
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
First I get that it begins with:
$('a[href*="#"]:not([href="#"])').click()
this says that every time you click on something with a href link to a '#'
then
if(location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname)
I have no idea what is that
neither this:
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1)
what is ".hash"? and what about the '?'? and the ':'?
the rest I got it.
thanks!
hash is the string that follows the #. So in the url index.html#path the hash will be path. The pathname checks if it's under the same original hostname and page, so it's a URL that points to the same page and will be scroll, if it's another page, scroll has no sense.
Ternary operators are like if() statements but in shorthand:
var a = (b == 1) ? "b equal one" : "b not equal one";
It's the same as:
var a;
if(b == 1) {
a = "b equal one";
} else {
a = "b not equal one";
}

Sleep function before smooth scroll

How can I add a 3 seconds pause before the smooth scroll?
The user will click on the button, then there will be a sleep of 3 seconds and then the smooth scroll will run.
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
You could add an setTimeout() like so:
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
setTimeout(function(){
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
}, 3000);
return false;
}
}
});
});
You could use the JavaScript-standard setTimeout() function:
JavaScript
setTimeout(function () {
// function that is executed after the timer ends
}, 3000);
As you can see, the setTimeout function takes two parameters: a handler (function) that will be executed after the timer ends, and an integer, that defines the timer duration in milliseconds.
If you are unfamiliar with all this "handling" concept, consider the below example instead, where we do the same, but first "save" the function in a variable:
JavaScript
var fnCallback = function () {
console.log('This plague works.');
};
// Call setTimeout() with a handler function (fnCallback), and an integer (3000)
setTimeout(fnCallback, 3000);

Categories