0

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?

2
  • 1
    When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. stackoverflow.com/help/mcve Commented Oct 31, 2016 at 15:31
  • 2
    your selector already return an 'array' of object, move the position var inside the function or use $(this).offset().top or left respectively Commented Oct 31, 2016 at 15:32

1 Answer 1

1

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 );

} );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.