Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default.

Below is the code snippet:

$("#ego").click(function(e){
    var $this = $(this);
    if($this.data('clicked', false)){
        hasScrolled();
    }
    e.stopPropagation();
});

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').animate({top:"-178px"}, 200, 'easeOutCubic');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').animate({top:"0px"}, 200, 'easeOutCubic');
        }
    }

    lastScrollTop = st;
}

Check out the fiddle here:

https://jsfiddle.net/antoniobarcos/wL2vuv4h/2/

Any suggestions?

Answer №1

it seems like you're looking to prevent the navigation bar from hiding at the top when clicking on a specific div:

To achieve this, you can add a class 'stopNavigation' on click of the button to your #ego. Additionally, adjust your conditional statement where you set the header's top position:

    $("#ego").click(function(e){
        var $this = $(this);
        $this.toggleClass('stopNavigation');
    });

and

        if (st > lastScrollTop && st > navbarHeight && !$('#ego').hasClass('stopNavigation')){
            // Scroll Down
            $('header').animate({top:"-178px"}, 200);
        }

I've made some updates to your fiddle for reference! Hopefully, this aligns with what you are trying to accomplish: https://jsfiddle.net/wL2vuv4h/3/

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

What could be causing the input submit in my form to be unresponsive when clicked?

I'm stumped on what's causing the issue. My sign-up form seems to be malfunctioning - when I click the "Complete Registration" button, nothing happens! The form doesn't even submit. Here is the HTML structure: <!DOCTYPE html> <html ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

What is the method for turning off Bootstrap for viewport width below a specific threshold?

I'm currently utilizing bootstrap for my website design. However, there's a particular CSS rule causing some frustration on one specific page: @media (min-width: 576px) .col-sm-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-w ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

What is the process for inserting a hyperlink onto an image within a query slider?

I am experiencing difficulties when attempting to add hyperlinks to the images in my slider. I have come to understand that images cannot be clickable in jQuery sliders, so I have tried the following in the HTML: <div class="wrapper"> <div class= ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

How can you eliminate a specific element from an HTML document?

Utilizing localStorage can be tricky when it comes to keeping the JSON file hidden from being displayed on the HTML page. One approach I used involves sending the JSON file to the client once and then performing all logic using that file. To prevent the JS ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

NodeJS error: Attempted to set headers after they have already been sent to the client

As a beginner, I have encountered an error message stating that the API is trying to set the response more than once. I am aware of the asynchronous nature of Node.js but I am struggling to debug this issue. Any assistance would be greatly appreciated. rou ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

eliminate the offspring of a component (chessboard)

Hey there! I'm currently working on developing a chess game and I could really use your expertise to help me solve an issue. In my code, when I try to move a piece in the game, this is what happens: 1. First, I remove the existing piece from its cu ...

Placing a FontAwesome icon alongside the navigation bar on the same line

Upon login, the navigation bar experiences display issues. Prior to logging in: https://i.stack.imgur.com/ZKyGe.jpg Following successful login: https://i.stack.imgur.com/zyP3m.jpg An obstacle I'm facing involves the Log Out fontawesome icon wrappi ...

Error TS2307: Module './tables.module.css' or its type declarations could not be located

Currently utilizing CSS modules within a create-react-app project and encountering an error within Google Chrome browser: https://i.stack.imgur.com/0ItNM.png However, the error appears to be related to eslint because I am able to close the warning modal i ...

Link together a series of AJAX requests with intervals and share data between them

I am currently developing a method to execute a series of 3 ajax calls for each variable in an array of data with a delay between each call. After referring to this response, I am attempting to modify the code to achieve the following: Introduce a del ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

What is the method for attaching multiple listeners to an element?

For example: v-on:click="count,handle" I posted this question in the Vue gitter channel, but received advice to use a single listener that triggers others. If using one listener is the recommended approach, I am curious to understand why. Is having multi ...

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

ajax duplicator and reset form tool

Hello everyone, I have a website where users can add their experiences. While adding an experience, they can dynamically add and remove more fields. One of the input fields is for a date, but when the data is submitted, the same date appears for all entrie ...