Frank
Frank

Reputation: 634

if-image-height JavaScript statement

I have a grid of several images on my website. Hovering on one of these images will display a label with a name and price. The problem is that some images have a smaller height, and then the label gets too close to the bottom. Now I'm trying to write a JS if-statement in order to decrease the margin-top of that label only if the image-height is less than 200px.

This is how my html looks like:

<div class="fw_preview_wrapper">
<img src="'.$row['imageURL'].'" alt="" class="fw_featured_image" id="product_image" width="540">
<span class="price_tag" id="price_tag"><span class="actual_price">€ '.$row['Price'].'</span>

As you can see, the image URL is variable and comes from a database via php. For the js function, I set id="product_image".

This is the CSS part:

span.price_tag {
top: 86%;
}

As you can see above, there is a margin top set to 86%. This very value needs to be changed to "80%" when an image has a height of less than 200px.

and finally, the JS part:

<script>
var img = document.getElementById('#product_image'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

if(height < 200){
$("span.price_tag").css('top','80%');
}
</script>

It doesn't work. I would appreciate some help. Thanks in advance!

Upvotes: 0

Views: 92

Answers (3)

Sarath Kumar
Sarath Kumar

Reputation: 2353

remove # from the element getting statement , we use # to specify id in Jquery and not in js try this..

  <script type="text/javascript"> 
   var img = document.getElementById('product_image'); 
   var width = img.clientWidth;
   var height = img.clientHeight;

   if(height < 200)
        $("span.price_tag").css('top','80%'); 
 </script>

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11859

in javascript you should be using:

var img = document.getElementById('product_image'); 

# is used in jquery like: var img = $("#product_image")

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Don't use hash # within param for getElementById:

var img = document.getElementById('product_image'); 

However you're using jQuery too, seeing your code, why not do just like this:

var img = $('#product_image'); 
var width = img.width();
var height = img.height();

if(height < 200){
$("span.price_tag").css('top','80%');
}

Upvotes: 1

Related Questions