views:

191

answers:

2

I've got this code that's changing a picture and additional link with it.

var imgSwap(pic, link){
    $("#sampleimg")
        .load(function () {   
           $(this).hide();
           $('#indexPic').removeClass('loading');
           $(this).fadeIn(500);
           })
        .error(function () {})
        .attr({src : picArray[5]});
    $("a.frontlink").attr("href", linkArray[0]);
    $('#indexPic').addClass('loading');
}

$("#arcade-button").click(function () { imgSwap(picArray[0], linkArray[0])});

The code works when I run the hole thing after each button, but not when I try to call my own function and optional-parameters. Can't seem to find the flaw... A little help anyone ?

+3  A: 

Try:

function imgSwap(pic, link){
    $("#sampleimg").load(function () {   
        $(this).hide();
        $('#indexPic').removeClass('loading');
        $(this).fadeIn(500);
    }).attr({src: pic});
    $("a.frontlink").attr("href", link);
    $('#indexPic').addClass('loading');
}

instead of

var imgSwap(pic, link){ /* further code */ }

Notice also that you name your parameters pic and link but use picArray[5] and linkArray[0] in the function body (thus hardcoding it).

And I think you don't have to provide an empty error function if you don't want that anything happens.

Felix Kling
or `var imgSwap = function(pic, link){ ... };`
munch
Thx for the answers. Messed up code in explanation :/ Didn't hardcode it like that IRL. (my first post here!). I'll try out your tips :)
VoodooBurger
@VoodooBurger: No problem, just ask when you have a problem. You can also edit your question to clarify it or explain better what you want to do. I mean, I know what you want to achieve but maybe you can explain the structure of your document better.
Felix Kling
:D it worked! Thx alot!Just to clarify. The meaning of the code is to shorten the amount of coding needed per event-listener. I just started using javascript, so now I'm trying to force myself not to hardcode things that much, as I just learned how to make functions :]
VoodooBurger
@VoodooBurger: You're welcome :) If the answer helped you, you should mark it as accepted.
Felix Kling
A: 

Its in a var right now, if you want to call it on your own you'd probably have to call it like instantiating a new object ex: new imgSwap(pic,link); Calling imgSwap(pic,link) in another way will treat it like an object and not execute the code inside.

Or just change it to be a function like @Felix said.

Harley Green