AdSense

Monday, December 04, 2017

How to display alt tag on image as text using jQuery

Have you ever had an image that you wanted to let a user click and display text? For example; Show hidden price? Hidden image/text game? Although most browsers support hover over the img element to display the "title", this does not work in most mobile browsers. Android allows tap and hold on the image to display the title, but iPhone does not. I've got an alternative solution. See below:

<html>
  <body>
    <script 
      src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <img 
      src="https://www.blogger.com/img/blogger-logotype-color-black-2x.png" 
      alt="my alt" 
      title="my title">
    <div id="show-text"></div>
    <script>
      $("img").on("click", function() {
        if( !$.trim( $('#show-text').html() ).length ) {
          $("#show-text").text($(this).attr("alt"));
        } else {
          $("#show-text").text("");
        }
      });
    </script>
  </body>
</html>


See an example in action at jsFiddle


Continuum (Aka Subspace)

Continuum (Aka Subspace)
Meet people from all over the world...then kill them. And it's free!