Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .css('right') not working

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'); 
     }
like image 625
Farhan Ahmad Avatar asked Feb 22 '26 04:02

Farhan Ahmad


2 Answers

"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)
like image 117
Rob W Avatar answered Feb 23 '26 18:02

Rob W


@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)
like image 26
Rifat Avatar answered Feb 23 '26 18:02

Rifat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!