Checking if the section id matches the href within an anchor tag using a jQuery if statement

Purpose: Ensure that the yes class remains on an element unless it is being added to another.

The code snippet below demonstrates this:

jQuery(function($){
    $(window).scroll(function() {
        var position = $(this).scrollTop();

        if ($('#services').length) {
            $('section').each(function() {
                var target = $(this).offset().top;
                var id = $(this).attr('id');

                //nested if statement should be included here

                if (position >= target - 79) {
                    $('.menu-wrap > ul > li > a').removeClass('yes');
                    $('.menu-wrap > ul > li > a[href*="#' + id + '"]').addClass('yes');
                }
            });
        };
    });

})

An additional nested if statement should be implemented to trigger position >= target when a menu item link (<a href="#~"/>) matches the id of any of the section elements on the page.

The necessary HTML structure is provided below:

<div class="menu-wrap">
    <ul class="nav"><li><a href="#home"/></li><li><a href="second"/></li></ul>
</div>
<section id="home"></section>
<section id="an-id-that-isnt-in-the-menu"></section>
<section id="second"></section>

Answer №1

Your revised if statement should look like this:

var selector = ".menu-wrap > ul > li > a[href=#" + id + "]";
if ($(selector).length) {

Here is the updated JS code:

jQuery(function($){
    $(window).scroll(function() {
        var position = $(this).scrollTop();

        if ($('#services').length) {
            $('section').each(function() {
                var target = $(this).offset().top;
                var id = $(this).attr('id');
                var selector = ".menu-wrap > ul > li > a[href=#" + id + "]";

                if ($(selector).length > 0) {
                    if (position >= target - 79) {
                        $('.menu-wrap > ul > li > a').removeClass('yes');
                        $('.menu-wrap > ul > li > a[href*="#' + id + '"]').addClass('yes');
                    }
                }
            });
        };
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with an Ajax form submission - struggling to retrieve the accurate value

Upon examining the code snippet below, it becomes apparent that when I utilize alert before initiating my ajax call, everything proceeds as expected and accurately displays the relevant information. However, upon attempting to transmit that data through PH ...

troubleshooting problems with jquery loading animations

My goal is to hide the menu, display an animated gif, hide the gif, and then show the updated menu. However, even though the menu disappears and reappears, the animated gif refuses to be shown. Where could I be making a mistake? $(document).ready(functio ...

Tips on ensuring that jQuery remains accessible following an AJAX request

jQuery(function ($) { $('input.adud').on('click', function() { var thisdiv = $(this).parents('div').attr("id"); var thisform = $(this).parents('form').attr("id"); var thistable = $(this).p ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

Ways to position two buttons in each corner with flexbox in a react js application

I'm fairly new to React JS and have just started building a simple React app. I'm trying to place two buttons on each side using CSS flex, but I'm having trouble achieving it. Can anyone help point out where I might be going wrong? im ...

AngularJS NG-Grid displaying incorrect value for select cell

I'm working on creating a table with a column that needs to be selected based on a value received from the server. The server sends me 4 as the value, but the first option is always selected instead. $scope.lotteryOptions = { data: 'myDa ...

Struggling to retrieve information upon form initialization using JavaScript in Yii2

When the salary form loads, I need to retrieve data from the ratechart model and populate certain text fields. In the Ratechart Controller, I have included: public $rateid = '1'; public function actionGetForRatechart($rateid) { $ra ...

Issue with Zebra_Calendar and JSON compatibility in Internet Explorer 7

I have integrated the Zebra_Calendar jQuery plugin on my website, but encountered an issue when including a JSON implementation. Specifically, I am facing an "Object Doesn't Support This Property or Method" error related to string.split during initial ...

When utilizing jQuery version 1.10.2, the HTML markup shows up prior to the page completing its loading process

I am trying to import one HTML page into another, but when I load or refresh the page, the HTML markup appears before the page fully loads. How can I fix this issue? <head> <script type="text/javascript" src="js/jquery-1.10.2.js" ></scr ...

Clicking on the radio button will automatically update the <span> element

I have a DIV that contains a list of radio buttons and a 'selected search' area (a <span>). When the 'selected search' area is clicked, a drop-down layer appears with the DIV containing the radio buttons. Upon selecting a radio bu ...

Adding Data Definition Language (DDL) statements while making an AJAX call

Is there a way to automatically update the value of a drop-down list whenever a partial view is loaded via an AJAX call? Currently, the AJAX call successfully retrieves the necessary information, but the user still needs to manually change the location val ...

"Troubleshooting the malfunctioning of the jQuery submit function in Begin

There is a partial view called contactaddpopup.cshtml which contains the following form for adding a contact: @using (Html.BeginForm("Validation", "Contacts", FormMethod.Post, new { id = "myForm"})) ...

Having trouble triggering drag events efficiently with d3-drag on SVG elements

drawAll refers to a two-dimensional array where each drawAll[i] element represents a drawing containing all the strokes. A stroke is essentially a string representing a series of 2D points that can be utilized to generate a <path>. I am currently at ...

Having trouble aligning elements in a single line using Bootstrap

I've been experimenting with different methods to align elements on the same line, such as using bootstrap and flexbox. However, I haven't been able to achieve the desired result. The goal is for the elements to stay on the same line even when th ...

Struggling to maintain the footer at the bottom of the page

I've been working hard to implement the tips from a tutorial on keeping the footer at the bottom of the page, especially when there isn't much content. The link to the tutorial can be found here: Despite following all the guidelines and properti ...

Easy Ways to Retrieve the Current Date and Time

Is there a way to retrieve the current date and time using angularjs I attempted the following method: <b>{{Date.Now}}</b> Unfortunately, this approach did not yield the desired results. Any tips or suggestions would be highly valued. ...

Having trouble with sending a POST request to a URL?

I'm attempting to communicate with an API by including the parameters in the URL. I am uncertain whether it will return XML or JSON, but it will be one of the two. Unfortunately, I keep encountering an error message. Here's an example of my requ ...

Guide to Obtaining Weight Data from a USB Scale

Looking for advice on how to import the reading from my USB weighing scale into an HTML form. I'm exploring options like Ajax/Js or Server side VBScript (classic asp) to accomplish this task. If anyone has recommendations on where I should start my s ...

How about incorporating an Ajax form within a partial view, or simply passing the data through in JSON format?

Seeking the ideal solution for my current task. In my grid, I showcase various data rows. I've made up my mind to update data for particular rows using ajax and a popup modal form. The dilemma lies in whether my ajax response should contain a parti ...

Utilizing nested single and double quotation marks in Javascript/jquery

For the longest time, I believed that single and double quotes were interchangeable in Javascript. However, I recently encountered a situation in a jQuery function that left me puzzled. Can anyone clarify why this code works: $('input:radio[name=&apo ...