Home > Blockchain >  Using a const in a URL onclick event
Using a const in a URL onclick event

Time:12-03

Im trying to build a cheaty kinda multilingual site in wordpress (interim fix) and need to set the logo link to go the the correct landing page when clicked, either /en/ or /se/.

Im trying to do this by grabing the url and then splitting the path name.

`

<script language="javascript" type="text/javascript">
const firstpath = location.pathname.split('/')[1];
</script>

<a href="/" onclick="location.href=this.href firstpath;return false;">
    <img  />
</a>

`

fairly sure im missing something simple, especially as it did work awhile ago until I changed something that i dont remember :/

When clicked the link shoulf return: root/first-folder-of-current-url

MORE DETAILS: (sorry fairly new here)

So I have a two folder hierarcy /en/ and /se/.

When in the /en/ folder if i click the logo I should be taken back to the root/en/ folder.

When in the /se/ folder if i click the logo I should be taken back to the root/se/ folder.

I cant have unique code for each folder so stuck trying to make this work with a javascript link.

CodePudding user response:

You can use a regular expression instead. (Regular expressions are how we look for patterns in strings of text in JavaScript. You can read about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)

Also, instead of using the onclick event, <a> tags already include a function for creating a hyperlink using JavaScript, by writing javascript: in the href attribute. That might be more compatible with WordPress.

In your case, it would go like this:

<a href="javascript:location.href=location.href.match( new RegExp( '^.*://.*/(en|se)/' ) )[ 0 ];">
    <img  />
</a>

This regular expression, ^.*://.*/(en|se)/, works like this:
^: Means [At the beginning of the string]
.*: Means [One or more of any character]
:// Means what it says, "://". This is in every URL, like https://www.google.com
.* Means [One or more of any character]
/(en|se)/ Means [Slash "/", followed by "en" or "se", followed by slash "/"]

The .match() function finds matches for the pattern we described, and returns them in an array. We only want the first entry of that array, so we specify .match( ... )[ 0 ]

CodePudding user response:

I found an alternative by simply replacing the content of the href:

<a href="#" id="homelink">
<img src="URL" />
</a>
<script>
document.getElementById("homelink").href ='/' location.pathname.split('/')[1];
</script>
  • Related