Reputation: 5198
I am making a simple game in jQuery. I am having trouble turning the spider image to north east. I have it working fine with north west but for some reason north east does not seem to be working. Here is my init code:
// JavaScript Document
function init(){
angel = $('<img class="spider">').attr({
'src': 'img/spider.png'
}).css({
width: "125px",
height: "125px;",
'position': 'absolute',
top: -10,
left: -10
});
//append it to body
$(document.body).append(angel);
//start dreaming
do_dream();
}
Here is my part of the code that is responsible for turning it north east or north west. Like I said earlier, north west seems to work perfectly fine but when the same code is used for turning it north east, it does not work.
// turn north west
if (parseInt(dream.css('top')) < parseInt(angel.css('top')) && parseInt(dream.css('left')) < parseInt(angel.css('left'))) {
$('.spider').attr('src', 'img/spider_nw.png');
}
// turn north east
if (parseInt(dream.css('top')) < parseInt(angel.css('top')) && parseInt(dream.css('right')) < parseInt(angel.css('right'))) {
$('.spider').attr('src', 'img/spider_ne.png');
}
Upvotes: 2
Views: 1549
Reputation: 7738
@rob-w had explained the reason and also had given a way to solve it.
Another way is, you can always set all the four properties- left, right, top, bottom. Don't need to set height and width then. Like -
//width: "200px",
//height: "200px;",
'position': 'absolute',
top: y - 100,
left: x - 100,
right: x + 100, //(x - 100 + 200)
bottom: y + 100, //(y - 100 + 200)
Upvotes: 2
Reputation: 349012
"Right" isn't working, because the CSS attribute for right
is set to "auto". You have to calculate the right offset, using (replace your current right-compare expression by this):
(dream.parent().width() - dream.width() - dream.offset().left) <
(angel.parent().width() - angel.width() - angel.offset().left)
Upvotes: 6
Reputation: 39950
At a guess, it's because a DOM element will only have the "bottom" and "right" attributes if it's been positioned with them. That is, the browser / jQuery will not automatically compute the distance from the right edge of the window / document for you when you do .css('right')
.
If what you want to find is the position of the right edge of the element, try adding the position of the left edge and the width.
Upvotes: 1