Site logo

Archived topic

Exclude some anchor link from smooth scrool when using function.php solution

7 replies · Started by Antonio on February 18, 2023

Viewing posts 1–8 of 8

Hello,
I've applied the following solution to have the smooth scroll behavior applied to all anchor links:

add_filter( 'generate_smooth_scroll_elements', function( $elements ) {
$elements[] = 'a[href*="#"]';

return $elements;
} );

This will generate some problems with navigation links in slider plugins (i.e. Smart Slider 3) as when the next/before navigation button is clicked, the page will in some case scroll to the top of the page.

I tried to exclude all the links not containing a particular string (i.e. #top), so I did the following:

add_filter( 'generate_smooth_scroll_elements', function( $elements ) {
$elements[] = 'a[href*="#"]:not(a[href*="#top"])';

return $elements;
} );

But this is not working (I assume it's because the href*="#"] condition is true for every "#top" anchor link.

What is the correct way to exclude some anchor links from the function? Could you please make 2 examples where:
- on the first example: all href*="#" links are targeted, excluding links containing "#top"
- on the second: all href*="#" links are targeted, excluding links containing "#top" AND "#middle"

Thank you

Hi there,

where are the Links on your site that you want Smooth Scroll to apply to ?

As those links have a role=button attribute, we can try excluding the role from the link. So try this selector.

a[href*=”#”]:not([role])

Hi,
it works, thanks!

What if I need to exclude other anchors with a role attribute?
Thank you

That selector will exclude any anchor with any role not just button.
Is that ok?

Hi David,
it's ok. Problem is: if I find other anchors to fix, then I'll have to open a new ticket.
Anyway, for the moment this solution works for me.
Thank you!

If you find any, let us know, as its hard to create a wild card selector that omits some elements without seeing them.\
Glad to be of help.

This archived topic is closed to new replies.