0

so I created a function that has 2 arguments for the css method, I run it but the arguments are getting read. The width values work on hover off and on, but w/e value i pass through in the arguments are getting read

function growImg(targetClass, imgClass, growPosition, growVal){
    $(targetClass).hover(
      function(){
        $(imgClass).css({'width': '25rem', growPosition : growVal});            
      },
      function(){
        $(imgClass).css({'width' : '12em'});
      }
    )
  }

// Calling function here
growImg('.img-profile', '.profile-img', 'top', '25px')

Any help would be great

0

2 Answers 2

4

You can use computed property names

$(imgClass).css({'width': '25rem', [growPosition] : growVal});

You can alternatively use shorthand property names

function growImg(targetClass, imgClass, top){
    $(targetClass).hover(
      function(){
        $(imgClass).css({'width': '25rem', top});            
      },
      function(){
        $(imgClass).css({'width' : '12em'});
      }
    )
  }

// Calling function here
growImg('.img-profile', '.profile-img', '25px')
Sign up to request clarification or add additional context in comments.

Comments

1

My guess is that the JavaScript is creating a key called growPosition and assigning the value of growVal to it. The reason being that JavaScript objects can be created without adding keys in quotes. There won't be a way for the parser to distinguish between a new object with a key called growPosition and the variable growPosition. Try using the object bracket syntax:

function growImg(targetClass, imgClass, growPosition, growVal){
    $(targetClass).hover(
        function(){
            var customCSS = { width: '25rem' };
            customCSS[growPosition] = growVal;

            $(imgClass).css(customCSS);            
        },
        function(){
            $(imgClass).css({'width' : '12em'});
        });
  }

// Calling function here
growImg('.img-profile', '.profile-img', 'top', '25px')

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.