JQuery: simple menu

I am trying to learn jQuery by following a simple menu. I have elements <div>that act like buttons and have links in them. I am trying to add onclick events to divs that navigate through the browser at the link address in the div. This is basically my pseudo code. What will the real code be? How can I improve this? Any feedback appreciated!

// Iterate over each menu button

$('.masterHeaderMenuButton').each(function () {

    // Get the link in each button and set the button onclick to 
    // redirect to the link address

    var url = $('a', this).attr('href');

    this.click(function () {
        window.location.href = url;
    });

    // If the user is on the page for the current button, hilight it

    if (window.location.href === url) {
        $('a', this).addClass("masterHeaderMenuButtonSelected");
    }
});
+3
source share
2 answers

Try this unverified example:

$('.masterHeaderMenuButton a').each(function () {

    // Get the link in each button and set the button onclick to 
    // redirect to the link address

    var _this = this; // save this ref for click handler.
    $( this ).parent().click(function () {
        window.location.href = $(_this).attr('href');
    });

    // If the user is on the page for the current button, highlight it

    if (window.location.href === url) {
        $(this).addClass("masterHeaderMenuButtonSelected");
    }
});
+1
source

jQuery , . , AJAX, HTML.

:

$('#nav_links li').live('click', function() {
    var ajax_link = $(this).attr('rel');                                      

    loadLink(ajax_link);
});

function loadLink(link){
    $('#content_window').css('position','relative');                              
    $('#content_window').animate({
        'left': '20px',
        'opacity': '0'
    }, 500, "swing", function() {

        $.ajax({
               url: '../sections/' + link,
               dataType: 'html',
               success: function(html) {
                   $('#content_window').html(html);
               }
        });
    });
}

, ?

HTML:

<ul id="nav_links">
    <li rel="setting-up.html"><span class="green">|</span>setting up<br></li>
    <li rel="features.html"><span class="purple">|</span>features<br></li>
    <li rel="more-uses.html"><span class="blue">|</span>more uses<br></li>
    <li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li>
</ul>

.

+1

Source: https://habr.com/ru/post/1743450/


All Articles