Jared
Jared

Reputation: 2483

jQuery dynamically position link-able image icon over draggable image

Can someone show me how to dynamically overlay an image (an icon in my case) in the upper right hand corner of an image no matter what the size of that image is. It needs to be able to work with the draggable ui so when the image is being moved the overlayed icon stays in its position.

I am rather new to jQuery and I have tried many things but cannot get a working example together. In the end the icon will need to be linkable so I can assign onClick functionality to it.

Can anyone show me some examples or point me in the right direction?

I am using the latest version of jQuery.

Upvotes: 1

Views: 1017

Answers (3)

Sampson
Sampson

Reputation: 268374

Since you want the icon to ultimately be clickable, I would avoid my gut intention to use :after on a containing element to show the icon. Instead, I would use a simple div wrapper with both your draggable image, and an icon inside:

<div class="draggable-image">
  <img src="http://placekitten.com/100/100" />
  <img src="help.png" class="icon" />
</div>

Then I would style the container to be inline-block, so that it matches the width (and height, for the most part) of its child img. This is also a good time to position the icon within the container:

.draggable-image {
  position: relative;
  display: inline-block;
}
.draggable-image img.icon {
  position: absolute;
  top: 10px;
  right: 10px;
}

Now we can bind up the draggable event, referencing the draggable image from within the ui.helper object provided to our various draggable methods:

$(".draggable-image").draggable({
  stop: function( event, ui ) {
    alert( $("img:first", ui.helper).attr("src") );
  }
});

Note I'm access the :first image, avoiding our .icon image. Lastly, we can bind some click logic to our .icon so that we can react to people clicking it:

$(".draggable-image .icon").on("click", function(){
  alert( "You've clicked the icon" );
});

Demo: http://jsbin.com/ihugas/3/edit

Upvotes: 1

TommyBs
TommyBs

Reputation: 9646

Could you not wrap them both in a "position:relative" div and make the div draggable? Then set the z-index of the image to 1 and the icon to 2 so it always sits on top? You can then just use "position:absolute; right:0px; top:0px" on the icon.

So similar to this

http://jsfiddle.net/qJHuf/1/

But the .image div would be an image, and .holder would be the draggable

Upvotes: 0

FiveTools
FiveTools

Reputation: 6030

position the icon absolute top left of a containing div (which holds the original 'background' image). Drag the div using draggable: http://jqueryui.com/demos/draggable/

Upvotes: 0

Related Questions