0

I have the following code working:

$(document).ready(function () {
    $(".b0").hover(function () {
        var src = $(this).attr('data');
        var href = $(this).attr('href');
        $("#imagen").attr('src', src);
        $("#vinculo").attr('href', href);
    });
    $(".b1").hover(function () {
        var src = $(this).attr('data');
        var href = $(this).attr('href');
        $("#imagen").attr('src', src);
        $("#vinculo").attr('href', href);
    });
})

But I can't simplify it with a function. I tried several times and ways...

1
  • Given that both event handlers do the exact same thing, just use $('.b0, .b1').hover(... Or better yet - put the same class on both elements Commented Nov 10, 2016 at 16:31

3 Answers 3

1

You can also use this:

 $(document).ready(function () {
        $(".b0 , .b1").hover(function () {
            $("#imagen").attr('src', $(this).attr('data'));
            $("#vinculo").attr('href', $(this).attr('href'));
        });
    })
Sign up to request clarification or add additional context in comments.

Comments

1

You could define the event handler in an external function, then access the element with event.currentTarget instead of this, with something like this:

$(document).ready(function () {

    function hoverHandler(event) {
        var src = $(event.currentTarget).attr('data');
        var href = $(event.currentTarget).attr('href');
        $("#imagen").attr('src', src);
        $("#vinculo").attr('href', href);
    }

    $(".b0").hover(hoverHandler);
    $(".b1").hover(hoverHandler);
})

Comments

0

If you want to create a function, you need to pass this to it explicitly.

function hoverHandler(element) {
    var src = $(element).attr('data');
    var href = $(element).attr('href');
    $("#imagen").attr('src', src);
    $("#vinculo").attr('href', href);
}      
$(".b0").hover(function() {
    hoverHandler(this));
});
$(".b1").hover(function() {
    hoverHandler(this));
});

But the simplest solution is to just combine the selectors:

$(".b0, .b1").hover(function () {
    var src = $(this).attr('data');
    var href = $(this).attr('href');
    $("#imagen").attr('src', src);
    $("#vinculo").attr('href', href);
});

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.