I have encountered a peculiar problem. It's strange to me because I can't figure out the root cause of it, despite trying everything in the Chrome Developer Tools debugger. Here is a snippet of code that works when I run it from a file on my desktop by opening it:
jQuery(document).ready(
function () {
Slider.initModule(jQuery('#slider'));
}
);
I'm importing jQuery as usual:
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
Here is the complete page. I am perplexed, as this should just be a simple example of a chat slider taken from "Single Page Web Applications" on Manning.
<!DOCTYPE html>
<html>
<head>
<title>Slider</title>
<style type="text/css">
body {
width: 100%;
height: 100%;
overflow: hidden;
background-color: #777;
}
#slider {
position: absolute;
top: 8px;
left: 8px;
bottom: 8px;
right: 8px;
border-radius: 8px 8px 0 8px;
background-color: #fff;
}
.slider {
position: absolute;
bottom: 0;
right: 2px;
width: 300px;
height: 16px;
cursor: pointer;
border-radius: 8px 0 0 0;
background-color: #f00;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var Slider = (function () {
var configMap = {
extendedHeight: 434,
extendedTitle: 'Click to retract',
retractedHeight: 16,
retractedTitle: 'Click to expand',
templateHtml: '<div class="slider"></div>'
}, $slider, toggleSlider, onClickSlider, initModule;
toggleSlider = function () {
var sliderHeight = $slider.height();
if(sliderHeight === configMap.retractedHeight) {
$slider.animate({height: configMap.extendedHeight})
.attr('title', configMap.extendedTitle);
return true;
} else if(sliderHeight === configMap.extendedHeight) {
$slider.animate({height: configMap.retractedHeight})
.attr('title', configMap.retractedTitle);
return true;
}
return false;
};
onClickSlider = function (event) {
toggleSlider();
return false;
};
initModule = function ($container) {
$container.html(configMap.templateHtml);
$slider = $container.find('.slider');
$slider.attr('title', configMap.retractedTitle)
.click(onClickSlider);
return true;
};
return {initModule: initModule};
})(jQuery);
jQuery(document).ready(
function () {
Slider.initModule(jQuery('#slider'));
}
);
</script>
</head>
<body>
<div id="slider"></div>
</body>
</html>
I cannot understand why the slider works when the above HTML is accessed through a file:/// URI in Chrome but fails to work when served over a localhost server. What could be causing this discrepancy?
Here's an intriguing update.
I inserted an alert into the toggleSlider function, and the pixel values differed from the CSS!
alert("HERE! " + sliderHeight);
I received a value of 15, whereas when I save the source code and open the file, I see 16! This inconsistency seems to be the reason why the slider isn't functioning correctly for me on localhost.