Is it possible to use a JQuery function after a page redirect has occurred

Take a look at this interesting fiddle!

View the Fiddle

I am interested in creating links that scroll to different sections of content areas on my site, similar to the footer links in the example. I have been suggested to use Anglers routing system, but I am not familiar with how API history or other methods actually work and how to implement them. Two other solutions I found are mentioned below:

Solution1? Solution2?

HTML

  <div class="content-slide-menu" data-menu="1">
            <ul class="menu">
                <li id="link1"> <a href="#null" data-page="1">blah blah</a>

                </li>
                <li id="link2"> <a href="#null" data-page="2">twit twoo</a>

                </li>
            </ul>
        </div>
        <div class="content-slide">
            <div id="page1" class="content">
                 <h3>blah blah</h3>

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh eros, commodo sit amet risus a, bibendum venenatis mi. In sed tempus ante. In ac molestie tortor. Proin convallis, diam facilisis volutpat blandit,</p>
                <div class="dots"><span>...</span>
                </div>
            </div>
            <div id="page2" class="content">
                 <h3>twit twoo</h3>

                <p>Quisque quis suscipit augue. Quisque eu augue eu elit imperdiet posuere. Integer tempor metus consectetur interdum porta. Fusce condimentum, metus eu commodo dapibus, diam metus vestibulum lacus,</p>
                <div class="dots"><span>...</span>
                </div>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div class="content-slide-menu" data-menu="2">
    

CSS

.content-slide-menu {
    float: left;
    width: 220px;
    padding: 0 10px;
}
.content-slide-menu li {
    list-style-type: none;
}
.content-slide-menu a {
    text-decoration: none;
    color: #2b2b2b;
    font-size: 135%;
}
.content-slide-menu a:hover {
    color: #3ca3c5;
}
.content-slide {
    float: left;
    width: 440px;
    margin-top: 65px;
}
.content-slide .content {
    display: none;
}
.content-slide .content h3 {
    font-size: 150%;
    font-weight: bold;
}
.content-slide .content p {
    margin: 5px 0;
    font-size: 110%;
}
.dots {
    font-size: 350%;
    font-weight: bold;
}
.active {
    color: #3ca3c5!important;
}

#footer {margin-top:800px;}
    

Script

 function showPage(menu, page) {
            $slider = $(".content-slide-menu[data-menu='" + menu + "']").first();
            $slider.next().children('.content').hide();
            $("#page" + page).show();
            $slider.find('a.active').removeClass("active");
            $("#link" + page).children().addClass('active');
        }
        function showAndScroll(menu, page) {
            showPage(menu, page);
            $('html, body').animate({
                scrollTop: $slider = $(".content-slide-menu[data-menu='" + menu + "']").first().offset().top
            }, 1000);
        }
        $(document).ready(function () {
            $(".menu a").click(function () {
                var $this = $(this),
                    $slider = $this.closest('.content-slide-menu');
                showPage($slider.data("menu"), $this.data("page"));
            });
            $(".content-slide-menu").each(function(index, that) {
                showPage($(that).data('menu'), $(that).find("a").first().data('page'));
            });
        });

Answer №1

Preventing the default hash jump execution on page load can be tricky, as each browser may behave differently.

In Chrome, a possible solution could be:

$(window).load(function() {
    $(window).scrollTop(0);
    //and do your animate scrolling
});

Another trick is to pass a hash that does not match an exact ID in your HTML but contains the page ID at least.

When writing your script, consider using the page parameter instead of menu based on your markup structure and desired outcome.

Script:

function showPage(page) {
    //show the target page and hide siblings
    $("#page" + page).show().siblings().hide();
    $("#link" + page).children().addClass('active').parent()
    .siblings().children().removeClass('active');
}

function showAndScroll(page) {
    showPage(page);
    $('html, body').animate({
        scrollTop: $("#link" + page).closest('.content-slide-menu').offset().top
    }, 1000);
}
$(document).ready(function () {
    $(".menu a").click(function () {
        var $this = $(this);
        showPage($this.data("page"));
    });

    $(".content-slide-menu").each(function () {
        showPage($(this).find("a").first().data('page'));
    });
    //on DOM ready get the hash value and extract the page id number 
    var hash = window.location.hash,
        page = hash.replace(/[^0-9]/g, '');
    //then execute showAndScroll to this page
    showAndScroll(page);

});

Ensure that links on your other pages are structured like this:

<a href="page.html#page-2" title="Example">Example</a>

Jsfiddle demo.

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

Preventing cross-site scripting attacks with the help of dynamic pre elements

An expert recommended that the user content, replyContent, be surrounded by a <pre> tag to prevent XSS attacks. However, why is it commonly believed that this code effectively prevents XSS? I attempted to inject </pre><script>alert("XSS" ...

Extracting raw data from the dojo.xhrGet request

When working with a JSP and servlet, I encountered an issue. In the JSP, I make an ajax call to the servlet which in turn calls a REST API to fetch JSON data. Using json.serialize(true);, I format the JSON data in the servlet before sending it to the front ...

How can you align a div next to another using the float property in CSS?

/*Custom Styling for Divs*/ #box1 { border: 1px solid; border-radius: 25px; width: 900px; } #box2 { border: 1px solid; border-radius: 25px; width: 430px; } #box3 { float: right; border: 1px solid; border-radius: ...

Ways to modify babel output file extensions

I'm facing an issue where babel --out-file-extension is not working as expected. Below is my package.json : { "name": "Assets", "version": "1.0.0", "description": "", "main" ...

What is the reason for utilizing letters as function name and parameters in JavaScript?

(function (a) { var r = a.fn.domManip, d = "_tmplitem", q = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, b = {}, f = {}, e, p = { key: 0, data: {} }, h = 0, c = ...

Determine if the value is present in every element of the array and return true

I am looking for a way to determine if all products have the status "Done" in their respective statusLog arrays. If any product does not contain "Done" or lacks the statusLog property altogether, then the function should return false. Although the current ...

Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly ...

Is it true that Redux Saga's select function returns mutable state?

Is the state returned by Redux Saga's select function mutable or immutable? To learn more, visit https://github.com/redux-saga/redux-saga ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...

The color of the text changes based on its alignment

Utilizing style sheets and attribute selectors, create styles that will change the color of text displayed on the page based on its alignment (e.g. left-aligned text in blue, right-aligned text in green). Additionally, text within h2 tags should have color ...

Unconventional JavaScript Variable Declaration

While going through some source code, I stumbled upon this peculiar variable declaration that has me a bit confused. let eventsEnabled : ?boolean = null; Can someone explain what exactly this means? You can find the source code here. ...

Delegation, substitution, and blending / jQuery

Seeking advice on a jQuery related matter - currently, I have a gallery-style script set up where clicking on thumbnails switches the larger image. The code snippet for this function is as follows: $('#thumbs').delegate('img','cli ...

Is it logical to steer users to a different page through a redirect?

This page serves as a logout feature that is activated through a jQuery post using a button. The code for the logout process is as follows: <?php session_start(); session_destroy(); header("Location: new location"); ?> When accessing this page dir ...

Tips for preventing duplicate entries in an AG Grid component within an Angular application

In an attempt to showcase the child as only 3 columns based on assetCode, I want to display PRN, PRN1, and PRN2. Below is the code for the list component: list.component.ts this.rowData.push( { 'code': 'Machine 1', &apo ...

The message from Vee-validate indicates that the validator 'required_if' does not exist within the system

I'm currently implementing vee-validate version 3 with Vue 2.7 in my project. Specifically, this is the entry in my package.json file for vee-validate: "vee-validate": "^3.4.5", My issue lies with getting the required_if rule to f ...

Several buttons sharing the same class name, however, only the first one is functional

As a newcomer to JavaScript, I am currently working on the front-end of a basic ecommerce page for a personal project. My query pertains to the uniformity of all items being displayed on the page, except for their names. When I click on the "buy" button f ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Using jQuery to toggle CSS properties

I'm having trouble switching between a CSS column layout and a normal layout for a div element with the ID 'article'. The jQuery script I wrote doesn't seem to work properly, as the entire thing disappears. Can anyone advise me on how t ...

Is combining form and fieldset causing issues?

My <form> for uploading an image and my <fieldset> for sending data via AJAX both work individually. However, when I try to merge them into one form, things get complicated. This is being done on a Node.JS server. Upload <form>: <for ...

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...