4

Ok, so I have a list of about 5 links, one after another. When I hover over one of these links, I need it to expand in size (to distinguish it from the others). And when I click on one of these links, I want it to update the image within a different element. I have figured out how to do this for a singular link using JQuery and CSS, but I am wondering if I need to create 4 additional (for the 4 other links) sets of JQuery functions, or if there is a way to conserve codespace by using for loops with a counter of sorts. My issue with the logic (of using just one all-encompassing function) stems from the fact that I do not know how to distinguish between links once they are hovered over. This makes me think I need a different set of functions for each link. Any and all advice is sincerely appreciated.

Here is my HTML code:

  <div class="interestsMarquee">

  <img src="sportsInterest.png" class="trigger" id="interest1" alt="sports" />
  <img src="sportsInterest.png" class="trigger" id="interest2" alt="music"  />
  <img src="sportsInterest.png" class="trigger" id="interest3" alt="hunting" />
  <img src="sportsInterest.png" class="trigger" id="interest4" alt="exercise" />
  <img src="sportsInterest.png" class="trigger" id="interest5" alt="shopping" />
  </div>

Here is my JQuery code:

    <script>
    $(function() {
var i = '1';

    $("#interest"+i).hover(function()
   {
     $("#interest"+i).css("width","115%")
               .css("height","70px")
               .css("margin-left","-10px");
    },function()
{
    $("#interest"+i).css("width","95%")
               .css("height","56px")
               .css("margin-left","3px");
        }); 

     $('.trigger').css('cursor', 'pointer')
         .click({id: 'myImage'}, changeImage);

function changeImage(e)
    {
var element=document.getElementById(e.data.id)
if (element.src.match("images/Cowboys.jpg")) 
{
    element.src="images/Countryside_bg.jpg";
    }
   else
   {
   element.src="images/Cowboys.jpg";
     }

    }

   });
     </script>

4 Answers 4

2

You don't need to use loops or additional JQuery functions on this case, with one selector you can match all the elements that you need. Also you shouldn't merge jQuery with pure Javascript code if you don't need. I rewrite your code, now is all in jQuery:

The HTML:

<div class="interestsMarquee">
  <img src="sportsInterest.png" class="trigger" data-index="1" id="interest1" />
  <img src="sportsInterest.png" class="trigger" data-index="1" id="interest2" />
  <img src="sportsInterest.png" class="trigger" data-index="1" id="interest3" />
  <img src="sportsInterest.png" class="trigger" data-index="1" id="interest4" />
  <img src="sportsInterest.png" class="trigger" data-index="1" id="interest5" />
</div>

The Jquery:

$(".interestsMarquee img").hover(function(){
    $(this).css(
          "width":"115%",
          "height":"70px",
          "margin-left":"-10px"
        );
    },function(){
    $(this).css(
         "width":"95%",
         "height":"56px",
         "margin-left":"3px");
}).click(function(){
    //Lets get the index of the img
    var index = ($(this).data('index');
    var src = "images/default_img.jpg";
    //Switch index to update src
    switch (index ) {
       case (1): src = 'images/image1.jpg';
                 break;
       case (2): src = 'images/image2.jpg';
                 break;
       case (3): src = 'images/image3.jpg';
                 break;
       case (4): src = 'images/image4.jpg';
                 break;
       case (5): src = 'images/image5.jpg';
                 break;
     }
     //adding the new src to the #myImage div
     $('#myImage').attr('src', src);
 });

The changes:

  • Like you are using .css you can push click() event after hover to match the same selector
  • Use $(this) when you are inside a event function
  • You can use attr('src') to get the src attribute.
  • Change multiple css properties in once steep

Fiddle: http://jsfiddle.net/sHxR3/

Update: I have updated my code to change the outer div img src depending of the clicked img.

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

7 Comments

Thanks for the help y'all, now I can hover over every one of the links individually and they expand (distinguishing themselves from the other links not being hovered over). Much appreciated. However, I would also like for the links I click on, that each different link will change the
<img id="myImage" </img> to a different image. I realize that this objective was not obviously apparent from my original question and I apologize. I also forgot to let you know (sorry @Tom Sarduy) that the <img> that would be changed was not the link image, but an image in a separate <div>. I was able to fix that easily, though, by just changing the $(this) to the actual id I wanted to alter. I think @silver99 may be on to something with the .each() function. However, I'm not sure where to take it from there.
@Connor: You can change another element src from the same .interestsMarquee img click event, like you said using the $('myImage') selector. Still Nn need to use each() on this case.
@TomSarduy I realize that Tom, but what can I do if I want to distinguish between the click events for the different.interestsMarquee images. There are 5 of the images in the <div> list, and I want the first image to change the $('myImage') to one certain image. I want the second image in the list (when clicked) to change the $('myImage') to a different image than what occurred in the first scenario. Does that make sense? Sorry I am probably misunderstanding your advice, but that is my issue.
oh, I see... best way to go is to add a data-index property to every img with value 1,2,3,4,5, then you can get that index using $(this).data('index'), I had updated my answer with the new code.
|
1

I'm going to try and answer your question by showing how you can improve your jQuery code and how to solve your problem in one go! :)

First off, you can simplify your code by refactoring the .css() calls into one call. This will make the entire code go faster since you wont be looping over the same element for each call of .css().

So that piece of code would go from

$("#interest"+i).hover(function() {
  $("#interest"+i).css("width","115%")
         .css("height","70px")
         .css("margin-left","-10px");
},function() {
  $("#interest"+i).css("width","95%")
         .css("height","56px")
         .css("margin-left","3px");
}); 

to

$("#interest"+i).hover(function() {
  $("#interest"+i).css({
    "width":"115%",
    "height":"70px",
    "margin-left":"-10px"
  });
},function() {
  $("#interest"+i).css({
    "width":"95%",
    "height":"56px",
    "margin-left":"3px"
  });
}); 

and lastly, and Adil beat me to it, you can bind the hover event to a class instead. And following his advice with the selectors as well are very good! :)

Hope this helps some! :)

Comments

0

take a look at the JQuery .each() function here

2 Comments

each() function is not needed on this case
@TomSarduy Sorry man I thought each() might help fix the problem after looking at the example code. Could you explain an alternative solution to my question in the comment above?
0

This should work:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery.js"></script>
<script>
    $(function(){
        $(".interestsMarquee img").hover(function(){
            $(this).css({"width":"115%", "height":"70px", "margin-left":"-10px"});
        },function(){
            $(this).css({"width":"95%", "height":"56px", "margin-left":"3px"});
        }).click(function(){
            src = $("#myImage").attr("src");
            if(src == "images/Cowboys.jpg"){
                $("#myImage").attr("src", "images/Countryside_bg.jpg");
            }else{
                $("#myImage").attr("src", "images/Cowboys.jpg");
            }
        });
    });
</script>
<title>Untitled Document</title>
</head>

<body>

<div class="interestsMarquee">
    <img src="sportsInterest.png" style="cursor:pointer;" alt="sports" />
    <img src="sportsInterest.png" style="cursor:pointer;" alt="music"  />
    <img src="sportsInterest.png" style="cursor:pointer;" alt="hunting" />
    <img src="sportsInterest.png" style="cursor:pointer;" alt="exercise" />
    <img src="sportsInterest.png" style="cursor:pointer;" alt="shopping" />
</div>

<img id="myImage" src="images/Cowboys.jpg" />

</body>
</html>

Hope it helps!

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.