White Arrow icon
Back to all Elements

Dynamically Inject current page URL to a Text element

Changing a text element by the page url using JavaScript

Using JavaScript I created a code that takes only the last part of the URL, and injects it to an element in the page.

The code basically creates 2 variables:

  1. Using 'window.location.pathname' it checks the URL and simplify it to get only the part after the Domain name, and any sub directories.
  2. Using 'array.length' checks to see how long the 1st variable is. If it is "0" long (no letters at all) then we must be on the homepage.

Then the code changes the element with the class name '.page-name' to one of the variables, depending on the result of the check we did on the 2nd variable.

Add the code to your site's custom code section before </body> tag, so the code will load on all the pages.

<script>

 var currentPage = window.location.pathname.substr(1).split("/").pop();

 var lngth = currentPage.length;

 

 $(document).ready(function() {

   if (lngth === 0) {

     document.querySelector('.page-name').textContent = "Home";

   } else document.querySelector('.page-name').textContent = currentPage;

 });

</script>

Copy

Now only thing left is to add a txt element (H1-H6, paragraph, txt, span, Link, Rich Text, Quote) on any page with the classname of 'page-name'.

Preview:

browser mockup
Share:
Heart icon

Michael's Vsauce was my gateway Youtube channel to the world of fun educational vlogs. This was the 1st video I stumbled upon.

Might also interest you:

Symbol in RichText

Cloneable
CMS
Code

Insert a symbol element into a RichText. On a static or dynamic page.

Read more
Blue arrow iconWhite Arrow icon

Pass Parameters

Cloneable
Code

Pass input fields parameters and add them to the destination URL.

Read more
Blue arrow iconWhite Arrow icon

Before / After effect

Cloneable
Tricks
Interactions

A Before / After effect for photos, without any code. Only Webflow's interaction.

Read more
Blue arrow iconWhite Arrow icon