Reputation: 31
I recently just started getting into html and was wondering how can I implement the following code and be more efficient and use an arrayList.
<!--
This was me just trying to play around with arrays and elements
var elements = document.getElementsByClassName("[id^=pop]");
var arr = jQuery.makeArray(elements);
-->
var p = $("[id^=pop]");
var position = p.position();
$("[id^=pop]").hover(function() {
$(this).css("cursor", "pointer");
$(this).animate({
width: "400px",
height: "400px",
top: position.top*.7,
left: position.left*.7
}, 150);
}, function() {
$(this).animate({
width: "300px",
height: "300px",
top: position.top,
left: position.left
}, 150);
});
As of now, when an image id equals pop0, and then another one equal pop1. They both will animate to the first image's height and width. How can I use an array so every img has its own position and won't be based off the first image that is loaded but rather their own top and left coordinates?
Upvotes: 0
Views: 277
Reputation: 21725
As mentioned in the comments, you need to move your position
variable from outside of your hover event handlers to inside your hover event handlers. This will set the context to the currently hovered item.
Currently your p
variable stores an array of all elements beginning with an ID that starts with pop
. Then you are storing a reference to the first element's position and never updating by setting the value of position
outside of your hover event handlers.
Here's an example with a small bit of caching so you're not always querying the DOM.
var $pop = $( '[id^=pop]' );
$pop.hover( function hoverIn() {
var $this = $( this ),
pos = $this.position();
$this
.css( 'cursor', 'pointer' ) // <= Possibly do this via CSS.
.animate( {
width: '400px',
height: '400px',
top: pos.top * 0.7,
left: pos.left * 0.7
}, 150 );
}, function hoverOut() {
var $this = $( this ),
pos = $this.position();
$this.animate( {
width: '300px',
height: '300px',
top: pos.top,
left: pos.left
}, 150 );
} );
Upvotes: 1