Amay
Amay

Reputation: 1521

jQuery img.src reset after click

I have problem with navigation.

HTML

<ul id="menu_bar">
    <li><a href="#home" class="hov selected"><img src="img/Home_on.png" alt="Home" />Home</a></li>
    <li><a href="#portfolio" class="hov"><img src="img/Portfolio_off.png" alt="Portfolio" />Portfolio</a></li>
    <li><a href="#about" class="hov"><img src="img/About_off.png" alt="About" />About</a></li>
   <li><a href="#contact" class="hov"><img src="img/Contact_off.png" alt="Contact" />Contact</a></li>
</ul>

JS

$(document).ready(function() {
    $("img.roll").hover(
        function() { this.src = this.src.replace("_off", "_over");},
        function() { this.src = this.src.replace("_over", "_off");}
    );
    $("a.hov").hover(
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_off", "_over");},
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_over", "_off");}
    );
    $("a.hov").click(
        function() {
            var img = $(this).find("img")[0];
            img.src = img.src.replace("_over", "_on");
            $("a.hov").removeClass("selected");
            $(this).addClass("selected");
        }
    );

});

I want to make on click function that will change anchor class, change img src inside of this anchor and when i use it on another anchor it will reset last clicked anchor to normal class and normal img src. Now my function remove class from all "a.hov", but not change img.src to "_off" for all this items, and don't know how make it.

Upvotes: 0

Views: 2964

Answers (2)

er-v
er-v

Reputation: 4465

$("a.hov").click(
        function() {

            $("a.hov").each( //Change all "_over" to "_off" for all items
             function() {
                 var img = $(this).find("img")[0];
                 img.src = img.src.replace("_over", "_off");
             });

            var img = $(this).find("img")[0];
            img.src = img.src.replace("_over", "_on"); //replace all "_over" (mabe all will work without this line)
            img.src = img.src.replace("_off", "_on"); //replace "_off"

            $("a.hov").removeClass("selected");
            $(this).addClass("selected");
        }
    );

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$("a.hov").click(
        function() {
            var img = $('img', this);
            console.log(img)
            img.attr('src', img.attr('src').replace("_off", "_on"));
            $('a.hov').removeClass("selected");
            $(this).addClass("selected");
        }
    );

Upvotes: 0

Related Questions