0

I have written this scirpt:

 $(document).ready(function () {
   $('#tb1 li').hover(function () {
    var head = $(this).attr("title");
    var image = $(this).find("a").attr("rel");
    $('.aCnt img').attr("src", image);
    $('.aCnt span').html(head);

   });
    $('#tb1 li').eq(0).hover();
}); 

I want to make this script global

function interActive(myID, myClass){
    ID = '#' + myID;
    cls = '.' + myClass;
     $('ID li').hover(function () {
    var head = $(this).attr("title");
    var image = $(this).find("a").attr("rel");
    $('cls img').attr("src", image);
    $('cls span').html(head);

   });
    $('ID li').eq(0).hover();
}

I know that jQuery function not similar to for example php functions. The interActive functions will not work in jQuery. How can I modify this function for jQuery? Thanks in advance.

1 Answer 1

4

The variables ID and cls are being treated literally as strings when put them inside quotes. You need to concatenate them like this: cls + ' img'.

function interActive(myID, myClass){
    var ID = '#' + myID;
    var cls = '.' + myClass;
    $(ID + ' li').hover(function () {
        var head = $(this).attr("title");
        var image = $(this).find("a").attr("rel");
        $(cls + ' img').attr("src", image);
        $(cls + ' span').html(head);

    });
    $(ID + 'li').eq(0).hover();
}

You may also consider writing a jQuery plugin for this, such as:

$.fn.interActive = function (target) {
    this.find('li').hover(function () {
        var head = $(this).attr('title');
        var image = $(this).find('a').attr('rel');
        $(target).find('img').attr('src', image);
        $(target).find('span').html(head);
    }).eq(0).hover();
};

Which can be used like this:

$("#someID").interActive(".someClass");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for help. Please see here: jsfiddle.net/EkKSS/1 .There is not any change in hover.
You used the first method, which doesn't create a jQuery plugin, so you call it simply using interActive(..., ...). You also need to put any strings (not variables containing strings) inside quotes. See updated fiddle: jsfiddle.net/gNFA3
Thanks for great plugin method.

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.