Home > front end >  JS Function from URL
JS Function from URL

Time:01-03

please help me. I have a code inside any of my posts.

post link is

link1    https://mysite.ext/mypost.html
link2    https://mysite.ext/mypost.html?id0987

    <script>
 let newuserid = window.location.search;
 if (newuserid = id0987) {
    aleret('Welcome, You reached throught ref id 0987');
 }
 </script>

I'm new to Code Life and I just create something like this. If someone comes up with 'link2' then run this function otherwise do nothing. The definition code is just one example.

Explain that if the URL of a post is post-url? Idxxxx. Then run the function xxxx. If the post url? Idyyyy Then run the function yyyy. The js code functions are already written in the current post. I know we can't create a function from a URL but a pre-written script can be run if the URL is like this do this. And in the URL we will track a referral ID.

CodePudding user response:

Give this a try

<script>
let urlID = window.location.href.indexOf('id0987');
if (urlID != '-1'){
alert('Welcome, You reached throught ref id 0987');
}
</script>

CodePudding user response:

YOU SHOULD PUT QUOTES here newuserid = "id0987"!! and i have also put .substr(1), it removes ? from the url.

window.location.search => "?id0987"
window.location.search.substr(1) >=> "id0987"

<script>
 let newuserid = window.location.search.substr(1);
 if (newuserid = "id0987") { //Here!!
    aleret('Welcome, You reached throught ref id 0987');
 }
 </script>

CodePudding user response:

you're using the 'if' statement. when you compare whether a value is equal, you need to use == and not =.

therefore:

 let newuserid = window.location.search;
 if (newuserid == 'id0987') {
    alert('Welcome, You reached throught ref id 0987');
 }
 </script>

would probably make your code work. notice i also wrapped id0987 with '' and changed aleret to alert.

another tip - in javascript you usually perform equals assertion using === - the triple equate operator makes sure that the type of the value is also the same.

but that's for a different question.

  • Related