user1179678
user1179678

Reputation: 11

How to create conditional hyperlink in HTML

I want to link my page with another page on condition.

Suppose I have 3 HTML pages, namely 1.html, 2.html and 3.html. What I want is that if 1.html is loaded then load page 2.html; If 1.html is not loaded then load 3.html.

please help.

Upvotes: 1

Views: 24823

Answers (3)

edgarator
edgarator

Reputation: 296

It should be something along the lines of: If you add the script at the bottom of the page, the javascript will search for all the <a> tags and compare them to the current url. If theres a match it will set its style to invisible.

<script>
linkNodes = document.getElementsByTagName("a");

for(i = 0; i < linkNodes.length; i++){
  if(linkNodes[i].getAttribute("href") == document.url){
    linkNodes[i].style.visibility= "hidden";
  }
}
</script>

This way if you are in 1.html, 2.html and 3.html are displayed but not 1.html itself. the same happens for 2.html which would show only 1.html and 3.html... etc.

Upvotes: 0

Jashwant
Jashwant

Reputation: 29025

I am not fully sure what you want to achieve.

I think you want to show hyperlink on a page only if some other pages are opened earlier.

If this is the case, you can create cookies on window.load of page 1, and check if that cookie is set on windolow.onload event of page 2.

If cookie is set, create a dynamic hyperlink on page 2 to redirect to page 3. If cookie is not set, do not create a link.

You may also show / hide hyperlink (instead of dynamically creating) depeding on whether cookie is set or not. This is an easy and crossbrowser way if you are not using jQuery.

Refer: http://www.w3schools.com/js/js_cookies.asp

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150070

I can't follow your explanation about pages 1, 2 and 3, but in a general sense you can have a hyperlink go to different URLs depending on some condition(s) by handling its "onclick" event to cancel the default navigation and do it from JavaScript instead:

<a href="defaulturlhere" onclick="doClick(); return false;">My link</a>

<script>
function doClick() {
   if (someCondition || someOtherCondition)
       window.location.href = "firstURLhere";
   else
       window.location.href = "alternativeURLhere";
}
</script>

The URL specified in the anchor's href attribute will be used if JavaScript is disabled. Otherwise, the doClick() function is called to decide which URL to navigate to. Of course the function can be as simple or complicated as you need.

The onclick needs to return false; to cancel the default behaviour of a click on the anchor because (obviously) the default is to navigate to the URL in the href attribute.

Upvotes: 1

Related Questions