3

I'm trying to follow this SO answer on how to tint an image, but when i do it, $("#myselector").height(); keeps been returned as 0. What am I doing wrong? Heres my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Test</title>
    <link rel="stylesheet" href="style.css">
    <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>

<script>
$(document).ready(function() {
  overlay = $("#overlay");
img = $("#myimg");
overlay.width($("#myimg").width());
alert($("#myimg").height());
overlay.height("100");
overlay.css("top", img.offset().top + "px");
overlay.css("left", img.offset().left + "px");

});


</script>

<body id="home">

<div id="overlay" class="overlay"></div>
<img id="myimg" src="building.png" />

</body>
</html>
Community
  • 1
  • 1
MissCoder87
  • 2,669
  • 10
  • 47
  • 82

3 Answers3

5

My best guess is that the image isn't loaded yet.

Your script runs onready. If you change it to onload you'll probably get a better result.

Change

$(document).ready(function() {

to

$(window).load(function() {

More: window.onload vs $(document).ready()

Community
  • 1
  • 1
Halcyon
  • 57,230
  • 10
  • 89
  • 128
4

Use image' load event:

$(document).ready(function() {
  overlay = $("#overlay");
  img = $("#myimg");
  img.load( function(){
    overlay.width($("#myimg").width());
    alert($("#myimg").height());
    overlay.height("100");
    overlay.css("top", img.offset().top + "px");
    overlay.css("left", img.offset().left + "px");
  });
});
Ivan Chernykh
  • 41,617
  • 13
  • 134
  • 146
1

Replace:

$(document).ready(function() {

on:

$(window).load(function() {
Michael
  • 15,386
  • 36
  • 94
  • 143
  • In an answer like this explaining what effect the change has is important. Why do you think `$(window).load` is superior to `$(document).ready` in this case? – Jason Aller May 01 '14 at 03:06