Skip to content
Advertisement

Make jQuery code run on page-change and load

I have a jquery code that inserts and prepends breadcrumbs on certain pages. I’m injecting this code through a third party tool where I can write JS. I only want these breadcrumbs for certain pages.

This was my original code that worked fine on desktop:

var style = document.createElement("style");
style.id = "Imdone";
style.textContent = ".breadcrumbs-mai{color:#555; font-size:14px; width:100%; padding:10px 5px;font-weight:200;}";
document.querySelector("head").appendChild(style);

require(['jquery'], function($){
  $(document).ready(function() {
    var bread = $('<div class="breadcrumbs-mai"><a href="https://www.norli.no">Hjem </a>/ <a href="https://www.norli.no/">Test </a>/ <a href="https://www.norli.no/">Test2 </a>/ <a href="https://www.norli.no/">test 3</a>/ <a style="color:#000; font-weight:600;" href="https://www.norli.no/">Test 4 </a></div>').prependTo('#page-title-heading');
  });
});

On mobile it didn’t load after changing category by clicking the li items. So I added $('body').change(runbread); to make it appear when switching category(page does not refresh on mobile when clicking a category, only does so on desktop).

But now, it loads twice for mobile and three times on desktop.

Here is my JS:

var style = document.createElement("style");
style.id = "Imdone";
style.textContent = ".breadcrumbs-mai{color:#555; font-size:14px; width:100%; padding:10px 5px;font-weight:200;}";
document.querySelector("head").appendChild(style);

require(['jquery'], function($){
  $(document).ready(function() {
    $("body").change(runbread);
  });
  
  function runbread(){
    var bread = $('<div class="breadcrumbs-mai"><a href="https://www.norli.no">Test </a>/ <a href="https://www.norli.no/">Test 2 </a>/ <a href="https://www.norli.no/">Test 3 </a>/ <a href="https://www.norli.no/">Test 4</a>/ <a style="color:#000; font-weight:600;" href="https://www.norli.no/">Test 5</a></div>').prependTo('#page-title-heading');
  }
});

How can I make sure it doesn’t load several times?

So, on mobile it should load on page-load AND re-load again when a li item is clicked(no page-reload, only content change). On desktop only on page-load.

Appreciate any help!

Advertisement

Answer

You can add $('#page-title-heading .breadcrumbs-mai').remove() to the start of your runbread function.

This will remove any other .breadcrumbs that might have been added before.

Advertisement