So here's the plan:
I wanted to create a simple static website with responsive images that load based on the browser width. I followed some suggestions from this link, but unfortunately, it didn't work for me. I tried all the answers and even attempted to change the CSS properties manually using:
$('.headerImg').css('margin','auto');
I also explored other ideas from the provided link, but it seems like my image just won't center properly. The test image displays correctly according to screen width, without any conflicting definitions in my CSS file. If anyone has a solution or clue, I would really appreciate it...
Here's a snippet of my code:
<html>
<head>
<title>broken</title>
<!--styling-->
<link rel="stylesheet" type="/styling/" href="styles.css">
</head>
<body>
<!-- Scripts-->
<script src="scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="scripts/constants.js"></script>
<!-- fetch and store screen sizes-->
<script type="text/javascript">
localStorage.setItem("windowWith", screen.width);
localStorage.setItem("windowHeight", screen.height);
localStorage.setItem("imageSize", getImageSize());
</script>
<!--Header-->
<div class="header">
<script type="text/javascript">
var path = "media/img/header_" + localStorage.getItem("imageSize") + ".jpg";
$(document).ready(function() {
$('.headerImg').attr("src", path);
});
</script>
<img class="headerImg"></img>
<br>
<div class="menuItems"></div>
</div>
<!--Middle-->
<div class="middle"></div>
<!--Footer-->
<div class="footer"></div>
</body>
</html>
Lastly, here's the JavaScript file used for determining which picture size to pick:
//const enum to define where
var width = {
large:1280,
medium:800,
small:460,
xsmall:330
};
//sets the size for the header image
function getImageSize(){
var size = "";
var screenWidth = localStorage.getItem("windowWith");
if(screenWidth > width.medium){
console.log("loading large picture");
size = "large";
}
else if(screenWidth <= width.medium && screenWidth > width.small){
console.log("loading medium picture");
size = "medium";
}
else if(screenWidth <= width.small && screenWidth > width.xsmall){
console.log("loading small picture");
size = "small";
}
else if(screenWidth < width.small){
console.log("loading xsmall picture");
size = "xsmall";
}
if(size == ""){
size = "xsmall";
console.log("Error - screen size not found - loading xsmall header");
}
return size;
}