0

I am coding an e-commerce website using XHTML in visual studio. At the moment to build the contact page I'm using Google API's to be able to show the store's location in an interactive map. My question is:

  • In case the user has the JS disabled in the browser how would I show a static image of the location without using the nonscript tag ah it is non XHTML compliant?

So far I have this within a few other elements in the body tag, only showing this to make the question easier to understand:

    <noscript><img src="map.png" class="map_location" /></noscript>
    <div id=map></div>

which interacts with a Javascript file

    function initMap() {
      var wannabemarker = { lat: 53.273301, lng: -2.817487 };
      var map = new google.maps.Map(document.getElementById('map'), {
    center: wannabemarker,
    zoom: 12
    });
var marker = new google.maps.Marker({
    position: wannabemarker,
    map: map
 });
}

The map works perfectly both with JS on and the static image shows if JS off but comes up with validation error and I have to make it disappear. Any help would be kindly appreciated.

Thank you

Jorge Guerreiro
  • 682
  • 6
  • 22

1 Answers1

1

The first thing to note is that you're plainly not really using XHTML, as the unquoted attribute in <div id=map> would break your page in browsers if you were. So really you're using normal HTML but probably thinking you are using XHTML because you've got an XHTML doctype.

So the best advice is simply to stop doing that. Use <!DOCTYPE html> instead and you can stop worrying about <noscript> being invalid in XHTML.

Now, in XHTML when used correctly, the invalid <noscript> element has no effect, but is default styled as display: none if JS is enabled and display:inline if JS is disabled. Note, that in either case, the contained img will be fetched from the server, whereas if you use normal HTML, the img will not be fetched if JS is enabled.

So, in XHTML you can do something like

<script>
   (function(){
       var css = '.noscript { display:none }',
           head = document.head || document.getElementsByTagName('head')[0],
           style = document.createElement('style');

       style.type = 'text/css';
       if (style.styleSheet){
         style.styleSheet.cssText = css;
       } else {
         style.appendChild(document.createTextNode(css));
       }

       head.appendChild(style);
   })();
</script>
<span class="noscript"><img src="map.png" class="map_location" alt="map" /></span>

and get the same effect of <noscript> in XHTML whilst being XHTML5 valid.


(Thanks to Christoph at How to create a <style> tag with Javascript for the JS pattern).
Community
  • 1
  • 1
Alohci
  • 78,296
  • 16
  • 112
  • 156