Replacing Text with an Image Using jQuery
I had a request from a customer recently who’s responsive site created a drop down menu when the users screen was under a certain size (standard for all responsive designs and done for mobile devices in this instance). The drop down menu on mobile simple displayed the text “MENU” though the user wanted to replace that with an image instead. Fortunately this is very simple to do with JavaScript, though I thought this was worthwhile to save here as a snippet in case it benefits other users as well.
The HTML in this example is as follows:
1 |
<a href="http://YOUR_HOME_PAGE.com" class="imageSwitch">MENU</a> |
1 2 3 4 5 6 |
$().ready(function () { $('.imageSwitch').each(function () { string = $(this).text('MENU'); $(this).html('<img src="YOUR_IMAGE_LOCATION/NAME.png" alt="' + string + '" />'); }); }); |
Obviously the image source (SRC) needs to change to the image location and name of your image. Likely you’ll have this image uploaded in your Resources section, which you can then click on the image and see the uploaded directory and name provided that you’ve already published your site.