Search code examples
javascriptjqueryhrefscrolltopmenubar

How to jump to hrefs of h2 for specific pages per JavaScript?


This is working (example is the id of an h2-Tag.):

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 54;
    $('a[href^=#]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 154;
    $('a[href^=#idofh2]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

This is not working (I want this function for all hrefs of h2 only for this pages -> https://example.com/, https://example.com/2.):

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 154;
    $('a[href^=#]').on('click', function(e){
        // Here you can see, that there is h2. I don't know where to place it.
        var href = $(this).attr('h2');
        $('html, body').animate({
            scrollTop:$(href).offset().top -menubarHeight }, 1);
    });
});

I am using 1, because I want to jump and no smooth scrolling. What can I use instead of .animate?

If I use this:

<script type="text/javascript">
jQuery(document).ready(function($){
    var menubarHeight = 54;
    $('a[href^=#]').on('click', function(e){
        var href = $(this).attr('href');
        $('html, body').css("scrollTop", $(href).offset().top -menubarHeight);
    });
});

then 54 dosen't works.

This:

$('a[href^=#]')

is generally for 54.

And this:

$('a[href^=#idofh2]')

is an id of one h2 tag of a page. That works. But how can I use it for all h2 tags and only for the pages https://example.com/, https://example.com/2? If I jump to an h2 tag, it has to be 154 (menubarHeight) otherwise 54.


Solution

  • Based on your question, I guess what you want to do is to set the menuHeight to either 154 or 54, depending if the target of the href points to a <h2> element or not. This is when jQuery's .is() method comes into handy.

    So, you can simply use the .is('h2') method to check if the selected node's tagname matches h2:

    jQuery(document).ready(function($){
        $('a[href^=#]').on('click', function(e){
            var href = $(this).attr('href');
    
            // Store the target element reference
            var $target = $(href);
    
            // Check if target element is a <h2> element
            var isTargetH2 = $target.is('h2');
    
            // Use ternary operators to set menuHeight
            // - If target element is <h2>, use 154
            // - Otherwise, use 54
            var menubarHeight = isTargetH2 ? 154 : 54;
    
            $('html, body').css("scrollTop", $target.offset().top - menubarHeight);
        });
    });