MoOx / pjax

Easily enable fast Ajax navigation on any website (using pushState + xhr)
MIT License
1.43k stars 124 forks source link

Remove CSS-Class from old link and attach "active"-class to selected link #218

Open Christian1998 opened 4 years ago

Christian1998 commented 4 years ago

Hi, ive a small problem and cant find a solution for it... I use the plugin normally, and its working fine. But after the loaded page i want to assign a CSS-Class to the clicked element (Menu and add class to the clicked item). Anyone a hint or a parameter i could use?

Thank you ))

donShakespeare commented 4 years ago

Please can you show how you use it? In the mean time, is this helpful?

new Pjax({
  elements: "a",
  selectors: [
    "body"
  ],
  switches: {
    "body": function(oldBody, newBody, options) {
        /*
          do anything you want here.
          $('body').find('.that-link').addClass('active'); //<-jquery code
        */
        oldBody.outerHTML = newBody.outerHTML;
        this.onSwitch()
    }
  });
Christian1998 commented 4 years ago

Hi @donShakespeare, thank you for your reply. All from pjax is working as well. This is my menu. Its working as expected but i want to add the class "active" to the clicked item. I dont know how to get the clicked element to attach the css-class.

grafik

I already tried it with: $(document).on('click', 'a[data-pjax-state]', function(e){ // do it } and document.addEventListener("pjax:click", function(options) { // do it } But it wont work :(

Edit: I found out that i could use the pjax:success-listener but it isnt very smart 🗡 Removed code-tag and moved it to pasteee: https://paste.ee/p/OV7CS

Any other idea? :D Thank you!

donShakespeare commented 4 years ago

I use something like what you have and works nicely. Make sure that link is not within any element that gets replaced by PJAX. You can test it by manually adding a class to said link via the browser console, then click to pjax, and see if you lose that class you added.

$(document).on('click', 'a[data-pjax-state]', function(e){
  $(this).addClass('activeStuff');
});

You can also use pjax:send

//Fired after the Pjax request begins.
//might be better than the above ... since it is catered for by pjax itself
  document.addEventListener('pjax:send', function(e){
    console.log(e);
    console.log(e.triggerElement);
    $(e.triggerElement).addClass('activeStuff');
  });
Christian1998 commented 4 years ago

Thanks for your suggestion. I'll try it next week and will reply here.

regards from switzerland :)