Tugce Aksoz
Tugce Aksoz

Reputation: 81

Change browser url

You can see my demo code on

https://codepen.io/Nyarl/pen/EORXMe

$(window).on('load resize scroll', function() {
        var activeFound = false;
        $('article').each(function() {
            if (!activeFound) {
                if ($(this).is( ':in-viewport( 5 )')) {
                    $("article.current-new").removeClass("current-new");
                    $(this).addClass('current-new');
                    var url = $(this).data('url');
                    var title = $(this).data('page-title');
                    document.title = title;
                    history.pushState('data to be passed', title, url);
                    console.log(url);
                    activeFound = true;
                }
            }

        });
    });
article {
      max-width:500px;
      min-height:500px
    }
    article.current-new {
      background:red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/is-in-viewport/3.0.4/isInViewport.min.js"></script>
<article data-url="https://stackoverflow/1" data-title="test">
      <p>
        <span>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente aliquam suscipit dolore non consequatur saepe provident vel molestias sequi, accusamus nemo consequuntur nisi ducimus aperiam illum cum expedita cumque tempora?</span>
    
      </p>
    </article>

I'm working on infinite scroll feature for my blog. I could change meta settings depends on element that has .current new class.

The problem is that when I try to change url, my code does it more than one time. Because of this, users has to hit browser's previous button more than once for reaching other posts.

I'm calling those article elements from an ajax call.

Edit: script src wasn't specified:

Upvotes: 3

Views: 241

Answers (1)

Anees Hikmat Abu Hmiad
Anees Hikmat Abu Hmiad

Reputation: 3560

You can prevent pushState to add url to history more than one time by using this:

if(!history.state || history.state.url != '/yourUrl'){
    // then push state
}

By history.state we will check if theres a history set or no, if yes, we need to make sure that this state not equal pushState url....

Note: pushState most be like this:

history.pushState({ url: "/yourUrl" }, title, url);

Upvotes: 1

Related Questions