Add Active Class when Scrolling and Clicking - javascript

I hope someone will be able to help me with my code, I want to add the active class when scrolling not just by clicking. How can I do that on my code. I'm not good at javascript or jquery. Thank you so much
jQuery(document).ready(function($) {
//you can now use $ as your jQuery object.
$('div p').click(function() {
$(this).addClass('active').siblings().removeClass('active');
})
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="article-links">
<p class="active">US Dollar rates and purchasing power are in all time low</p>
<p>Huge institutional interest</p>
<p>Strong fundamental growth and usage on overall blockchain ecosystem</p>
</div>

Your code works. It might be more obvious with a noticeable change. I've styled the active class to increase font-size.
jQuery(document).ready(function($) {
//you can now use $ as your jQuery object.
$('div p').click(function() {
$(this).addClass('active').siblings().removeClass('active');
})
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') &&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
});
.active {
font-size: 24px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="article-links">
<p class="active">US Dollar rates and purchasing power are in all time low</p>
<p>Huge institutional interest</p>
<p>Strong fundamental growth and usage on overall blockchain ecosystem</p>
</div>

Related

Smooth Scrolling not working correctly

I've been bashing my head against the wall trying plenty of smooth scrolling plugins to work why the signup button won't smooth scroll down to the #target section properly.
Please help hive mind, I am using CSS tricks code.
$('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 can see the pen with all the html css and other js at
https://codepen.io/samducker/pen/RVoORy
Cancel your code and try out this one (It's maybe a bit fast change it maybe to 500), it might be a bit laggy if you have so much content between your button and the anchor:
/*Scroll Down Button*/
$(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;
}
}
});
});
Your jQuery selector seems to be incorrect. Therefor the click function will not fire when you click on the button and will fallback to it's default anchor behavior. I forked your codepen and changed the jQuery selector to a see: https://codepen.io/anon/pen/VbmNXd
Try to change the jQuery selector to what works for your application.

Scroll to the anchor

Code:
function scroll_page(){
var target = document.location.hash.replace("#","");
var selector = 'div[id='+target+']';
alert(selector);
$('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
return false;
};
Сode is called here:
$(window).on('hashchange', function() {
scroll_page();
});
The problem is that when you click on the link jumps sharply to this div , and then gently pulls up to its top .
If you have an anchor in your link like <a href='#id'>, then it will trigger before your JavaScript. hashchange event occurs after the scrolling to the anchor.
To prevent this, you need to bind to click event and prevent default behaviour.
I would do something like this.
HTML:
<a class="slow-scroll" href="#first">First</a>
<a class="slow-scroll" href="#second">First</a>
<a class="slow-scroll" href="#third">First</a>
JS:
$(".slow-scroll").on('click', function(e) {
var target = $(this).attr("href").substr(1);
var selector = 'div[id='+target+']';
alert(selector);
$('html,body').animate( {scrollTop: $(selector).offset().top -60}, 2000);
e.preventDefault();
return false;
});
Here is the JSFiddle Demo.
Try the following code,
$(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 - 140
}, 1000);
return false;
}
}
});
});

Scroll to anchors

I'm trying to code a menu for my website that has the possibility to scroll to anchors on the same page and anchors on different pages.
The first one is working. The code is:
$(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;
}
}
});
});
The menu is the same on every page, I can't edit his code on each page. So the HTML code basically is:
<a id="mylink" href="http://www.mcsoftware.com.br/sitemc/#allcontentcontact"><span>Contato</span></a>
<a id="mylink2" href="http://www.mcsoftware.com.br/sitemc/#bluecontent"><span>Parceiros</span></a>
And I'm using javascript to detect if the user is on the homepage, and if he is, it changes the href behaviour, because it's only on the homepage that the anchors are on the same page of the menu. Look:
var url = "http://www.mcsoftware.com.br/sitemc/";
$(function(){
if (location.href==url){
$('#menu #mylink').attr("href","#allcontentcontact");
$('#menu #mylink2').attr("href","#bluecontent");
}
});
Now, the problem is the second part of what I've said on the beginning of the post: Scroll to anchors on different pages.
So, what script should I use to do the trick and doesn't affect everything that I've already done? Is it possible?
(And the code need to hide the "#nameoftheanchor" from the URL, like the first code already do)
Thanks!
I did something that is working really well! But still shows the "#anchortag" on the URL when the anchor is on another page.
<script>
var url = "http://www.mcsoftware.com.br/sitemc/";
if (location.href==url) {
$(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;
}
}
});
});
} else {
var jump=function(e)
{
if (e){
e.preventDefault();
var target = $(this).attr("href");
}else{
var target = location.hash;
}
$('html,body').animate(
{
scrollTop: $(target).offset().top
},2000,function()
{
location.hash = target;
});
}
$('html, body').hide();
$(document).ready(function()
{
$('a[href^=#]').bind("click", jump);
if (location.hash){
setTimeout(function(){
$('html, body').scrollTop(0).show();
jump();
}, 0);
}else{
$('html, body').show();
}
});
}
</script>
any help?
To answer your second question, the browsing history can be changed using
window.history.pushState() and
window.history.replaceState().
For how to use each function, see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
window.location.pathname will retrieve the current url path. So combining these concepts, I came up with the following:
history.pushState("", "", window.location.pathname);
This should remove the hash while keeping the rest of the url in-tact. If this doesn't solve your problem, hopefully it will at least get you started on the right path.

Conflicting "back to top" scripts - how to fix?

I'm using 2 scripts found on the internet, one for a smooth scroll to a DIV at the bottom of the page, and one for a smooth scroll "Back to top". The issue is that there's a conflict between both and therefore the "back to top" one doesn't work (no back to top on click). Used independently they both work perfectly.
How could I "merge" them both into one single script? (and keep the fade-in fade-out effect of the back to top script) See http://jsfiddle.net/GjsVq/1/
Many thanks
$(document).ready(function() {
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
$(document).ready(function() {
var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.back-to-top').fadeIn(duration);
} else {
jQuery('.back-to-top').fadeOut(duration);
}
});
jQuery('.back-to-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
})
});
$('a[href^="#"]').on(... is selecting both <a> elements. One approach is to either rewrite this selector to match only the <a> elements that should force a scroll to the bottom (maybe use a CSS class for this?)
An alternative, quick-and-dirty fix would be to reset the event handlers on the "back-to-top" element before attaching its own click handler: jQuery('.back-to-top').off().click(...
I normally just use one smooth scroll function and then set my "go to top" button with a href="#idOfHighestElementOnPage". This is the smooth scroll function (which may include something helpful if you don't want to go the same route I went):
$(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 - 100
}, 'normal');
return false;
}
}
});
})
window.onscroll = scrollFunction;
function scrollFunction() {
var doc = document.documentElement, body = document.body;
var top = (doc && doc.scrollTop || body && body.scrollTop || 0);
if (top > 200) {
$('.back-to-top').fadeIn();
}
else {
$('.back-to-top').fadeOut();
}
}

smooth scroll and accordion conflict bootstrap

although this has been asked a few times I haven't found something which will fix my problem.
This is my code for the smooth scroll:
$(function() {
$('a[href*=#]:not([href=#]),a[href*=#]:not(a[data-toggle])').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;
}
}
});
});
it's css-tricks code with a bit of editing.
This is the site: http://redrocketwebsitedesign.co.uk/test/my3DtwinAlpha/about/#arrow6
So the accordion is still being selected for the scrolling, and it's not running the accordion js.
I think there's a problem with my javascript not selector code :
a[href*=#]:not(a[data-toggle])
Any help appreciated :-]
This is what you are really looking for :
$('a[href*="#"]:not([href="#"]):not([data-toggle])').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;
}
}
});
:not([data-toggle])
is to avoid smooth scroll with bootstrap tab, carousel etc...
The page you provided has a mistake in code:
$('a[href*=#]:not([href=#]),'a[href^="#"]:not([data-toggle])').click(function() {
^^^ - extra and unnecessary character
So your handler is not set.
You can also consider specifying the class of the element(s) that should trigger a smooth scroll animation (thus excluding others, such as the accordion tabs), like this:
$('a[href*=#][class*="smooth"]:not([href=#])').click(function()
Or vice versa, specify the class of the element(s) that shouldn't trigger the script (in this case we exclude the class of the links that trigger the accordion effect):
jQuery('a[href*=#]:not([href*=#][class*="accordion-toggle"])').click(function()
var headp = $(".pixxett-header").innerHeight();
var stick = $(".pixxett-header.sticky").innerHeight();
$(document).on('click', 'a[href^="#"]:not([href="#"]):not([data-toggle])', function (event) {
event.preventDefault();
if (scroll == 0){
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - stick}, 500);
}else{
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top - headp}, 500);
}
});

Categories

Resources