Garfield
Garfield

Reputation: 2537

How can I find the y-position of background image in pixels using JavaScript?

I have a background image set up using following code.

background-image: url('url');
background-position: center;
background-size: contain;

This will place the image on center of div.

enter image description here

Is there any method or calculation to find the width(question mark in image) in pixel?

Upvotes: 0

Views: 1209

Answers (2)

MJC
MJC

Reputation: 3939

Let's assume you don't know the image ratio.

//getting the image URL (code from [here][1])
var url = $('CONTAINER_SELECTOR').css('background-image').replace(/^url\(['"]?/,'').replace(/['"]?\)$/,'');

//creating the image
var img = new Image;

img.src = url;

//WARNING: Im not dealing with the "image loaded" question.

var ratio = null;
if(img.height){
   ratio = img.width / height;
}


var containerWidth = $('CONTAINER_SELECTOR').innerWidth();

var difference = ($('CONTAINER_SELECTOR').innerHeight() - (containerWidth / ratio)) / 2);

I didn't test it. Later on I'll do a jsfiddle if necessary.

BEWARE: The code above might need tweaking when the ratio of the container is below 1 and the image's ratio is above 1 and vice-versa.

Upvotes: 1

Arun
Arun

Reputation: 1185

You can use like

<body>

<div>
  <p>Hello</p>
</div>
<p></p>

<script>
var p = $( "p:first" );
var position = p.position();
$( "p:last" ).text( "left: " + position.left + ", top: " + position.top );
</script>

</body>

or

<script>
var p = $( "p:last" );
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
</script>

Upvotes: 0

Related Questions