Dysan Posted May 22, 2008 Share Posted May 22, 2008 Hello! How do I display the code for a DIV within the page source only if JavaScript is turned on? (If JavaScript is disabled, then the DIV code shouldn't be visible within the page source) Also, if JavaScript is turned on, how do I show/hide the div, upon clicking a link? If JavaScript is disabled, then this link should navigate to a different page (e.g. google.co.uk) Quote Link to comment https://forums.phpfreaks.com/topic/106766-javascript-only-div-code/ Share on other sites More sharing options...
KevinM1 Posted May 22, 2008 Share Posted May 22, 2008 Hello! How do I display the code for a DIV within the page source only if JavaScript is turned on? (If JavaScript is disabled, then the DIV code shouldn't be visible within the page source) Are you talking about actually hiding the div from the page source (i.e., when a user chooses "View Source")? If so, then the only way I can think of 'hiding' that bit of the source code is to have your script dynamically create the element and its content: <html> <head> <title>Element creation test</title> <script type="text/javascript"> window.onload = function() { var myDiv = document.createElement("div"); var myText = document.createTextNode("This is a dynamically created div"); var myBody = document.getElementsByTagName("body")[0]; myDiv.appendChild(myText); myBody.appendChild(myDiv); } </script> </head> <body> </body> </html> If JavaScript isn't enabled, then the div isn't created, so it won't show up in the source code. Note that I didn't use myDiv.innerHTML = something. In my experience, things added to an element using innerHTML never show up in the source at all, so it's useless if you want dynamically created markup to appear in the source. Also, if JavaScript is turned on, how do I show/hide the div, upon clicking a link? If JavaScript is disabled, then this link should navigate to a different page (e.g. google.co.uk) This is pretty simple. Modifying the code above: <html> <head> <title>Element creation test</title> <script type="text/javascript"> window.onload = function() { var myDiv = document.createElement("div"); var myText = document.createTextNode("This is a dynamically created div"); var myBody = document.getElementsByTagName("body")[0]; myDiv.appendChild(myText); myBody.appendChild(myDiv); var testClick = document.getElementById("testClick"); testClick.onclick = function() { myDiv.style.display = (myDiv.style.display == 'none') ? 'block' : 'none'; return false; } } </script> <style type="text/css"> div { display: none; } </style> </head> <body> <a id="testClick" href="http://www.google.com/">Click me!</a> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/106766-javascript-only-div-code/#findComment-547329 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.