Make all Images responsive with bootstrap automatically!

Hi guys, in this post we will see how to make all images on your website responsive automatically with bootstrap. this will get rid of the problem of the images breaking out of the content area of your website on any kind of display.

I have written a simple script that will apply the img-responsive bootstrap class to all your images.


before beginning, make sure you have linked the bootstrap stylesheet file in the head section of your website.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

Now, Paste this script just before </body> tag

<script>
var totalImg = document.getElementsByTagName("img").length;
for(var i = 0; i < totalImg; i++){
var img = document.getElementsByTagName("img")[i];
var att = document.createAttribute("class");
att.value = "img-responsive";
img.setAttributeNode(att);
}
</script>

basically, this script creates a class attribute for all img elements and gives it img-responsive value

Full Example: Link

Leave a Reply

Your email address will not be published. Required fields are marked *