سؤال

So I have 2 links that I would like to show if javascript is on and hide when it is off, and when the javascript is off, I would like to show 2 other links in its place with noscript tag.

What I have so far is:

-js here- show 2 links if js is on and hide when it is disabled -js here-

-noscript- link 1 link 2 -noscript-

I only have experience in PHP and am not very familiar with javascript.

What would be the best way to go about this? Should there be a javascript function of some kind to make the show/hide function work? But if javascript is off, how will the function run to hide the links?

If someone can point me in the right direction to go about this or provide me with a simple code snippet, I would really appreciate it. Thanks!

هل كانت مفيدة؟

المحلول

  1. Hide the links using CSS - not visible by default

    <a id="link1" href="#" style="display: none">Script link 1</a>
    <a id="link2" href="#" style="display: none">Script link 2</a>
    
  2. Show the links using Javascript - they are only visible if Javascript is on, of course

    <script type="text/javascript">
         document.getElementById('link1').style.display="block";
         document.getElementById('link2').style.display="block";
    </script>
    

    Depending on what you need, you can use any other display property (link is inline by default, I added block here, use whichever you need).

  3. Add the noscript stuff - only visible when Javascript is off

    <noscript>
    -two other links-
    </noscript>
    

نصائح أخرى

I've often seen this done with a CSS class on the BODY tag. For example:

<html>
<head>
  <style type="text/css">
    BODY A { display: none; }
    BODY.script A { display: inherit; }
  </style>
</head>
<body>
    <a href="#">Shows with Script</a>
</body>
</html>

You can then use the script:

document.body.className = 'script';

For browsers that support Javascript, the script CSS class will be added and BODY.script styles will be used. Otherwise, regulard BODY styles will be used.

You can then define exactly how you want any element on the page to display with or without script enabled. Likewise, you could reverse this and give BODY a noscript style, then remove it through script.

JSFiddle Link

You can also do it without noscript, as follows

HTML

<a href="" style="display:none" id='javascript_link1'>JS link-1</a>
<a href="" style="display:none" id='javascript_link2'>JS link-2</a>
<a  href="" id='nonjs_link1'>link-1</a>
<a href="" id='nonjs_link2'>link-2</a>

JS

document.getElementById('javascript_link1').style.display="block";
document.getElementById('javascript_link2').style.display="block";
document.getElementById('nonjs_link1').style.display="none";
document.getElementById('nonjs_link2').style.display="none";​

DEMO.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top