Question

I saw this question and found it helpful, but I tried doing more with the code to apply zoom buttons and can't seem to get it to work properly. I'm new to javascript and jquery and I'm having trouble understanding how the "this" keyword is applied.

$('#plus').click(
function( event ){
    var scale = 150/100;
    var pos = $('#Container img').offset();
    var clickX = event.pageX - pos.left;
    var clickY = event.pageY - pos.top;
    var container = $('#Container img').parent().get(0);

    $('#Container img').css({
        width: this.width*scale, 
        height: this.height*scale
    });

    container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
    container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);

$('#minus').click(
function( event ){
    var scale = 100/150;
    var pos = $('#Container img').offset();
    var clickX = event.pageX - pos.left;
    var clickY = event.pageY - pos.top;
    var container = $('#Container img').parent().get(0);

    $('#Container img').css({
        width: this.width*scale, 
        height: this.height*scale
    });

    container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
    container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);

I made a jsfiddle to demo my code.

Was it helpful?

Solution

this refers to the clicked element (actually, you should probably be using $(this) in jQuery), because the function that's called after the click gets that scope. So in your example, this refers to either the plus or the minus button, therefore you're techically scaling their width/height and applying the resulting width/height to the image.

A common thing to avoid having to debug what this represent is to assign it to a variable at the very top of the function, for example:

var self = this;

or

var $myClickedButton = this;

Also, pay attention to styling:

  • element.width refers to an element's width attribute (like <img width="300" />, similar to jQuery's $(element).attr('width')), but
  • element.style.width refers to its CSS width (like <img style="width: 300px;" />, or <img class="myClassWithDenotedWidth" />, similar to jQuery's $(element).css('width')). The latter also has a unit, so you have to parseInt it to get just the numeric value.

I've fixed it for your plus button, you can follow the same principle for the minus. Here's what I did:

    var $image = $('#Container img');
    var container = $image.parent().get(0);

    $('#Container img').css({
        width: Math.round(parseInt($image.css('width'), 10) * scale), 
        height: Math.round(parseInt($image.css('height'), 10) * scale)
    });

See it here: http://jsfiddle.net/shomz/4A9Gt/4/ (also added a CSS transition to make zooms less choppy)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top