简体   繁体   中英

Change DIV Class on Anchor Click

I've seen a few similar posts but I don't have much of an understanding of Javascript so I'm wondering if you can help.

I have the following code, which when a main menu link is clicked (eg #contact ) changes the CSS Class of <div class="contact"> and adds a few extra classes in order to make the previous page disappear and the new page reappear:

$('.top-menu').on('click', 'a', function(){

    /* vars */
    var width = $(window).width();
    var id = $(this).attr('href');
    var h = parseFloat($(id).offset().top);
    var card_item = $(id);
    var menu_items = $('.top-menu li');
    var menu_item = $(this).closest('li');
    var d_lnk = $('.lnks .lnk.discover');

    if((width >= 1024)) {
        
        /* if desktop */
        if(!menu_item.hasClass('active') & (width > 1023) & $('#home-card').length) {

            /* close card items */
            menu_items.removeClass('active');
            container.find(card_items).removeClass('animated '+animation_in);

            if($(container).hasClass('opened')) {
                container.find(card_items).addClass('animated '+animation_out);
            }

            /* open card item */
            menu_item.addClass('active');
            container.addClass('opened');
            container.find(card_item).removeClass('animated '+animation_out);
            container.find(card_item).addClass('animated '+animation_in);
            
            $(card_items).addClass('hidden');
            
            $(card_item).removeClass('hidden');
            $(card_item).addClass('active');
        }
    }

Is it possible to tweak this code so that any link with a changepage class will also have the same behaviour?

And as a further improvement, is it possible to get this function to happen based on the current page URL/on page load, so that it happens if a user gets sent to the contact page of the website (so they don't have to click the contact page, it would just automatically load).

Thanks in advance for your support.

Please try to fix if statement with below(remove:):

if(menu_item.hasClass('active') & (width > 1023) & $('#home-card').length)

These code lines are strange each other: id is getting jquery object, then it goes into $().
This makes conflict.

var id = $(this).attr('href');
var card_item = $(id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM