Sony packman
Sony packman

Reputation: 840

Avoid repetition by passing in a value

I'm inserting images into dom with javascript and I would like to pass in the second classname and some other properties of the images while calling the function.

So I have functions containing code this:

function movieCreator(movieName){

'<img class="clip terminator" src="images/terminator.png" onclick="imageControl(this);" alt="terminator" />','

};

 function movieCreator(movieName){

'<img class="clip rambo" src="images/rambo.png" onclick="imageControl(this);" alt="rambo" />'

 };

There is some other stuff inside those functions too but I'm trying to simplify the question a bit. I would like to pass in the words "terminator" and "rambo" while calling the functions like

movieCreator(terminator);
movieCreator(rambo);

but my head gets really stuck while I try to think where to place the quotes and things like that in order to replace those words correctly from the code.

So my question is this: what would be the correct syntax of replacing the word "terminator" with a dynamical value that is passed in when the function is called?

Upvotes: 0

Views: 153

Answers (6)

just.another.programmer
just.another.programmer

Reputation: 8815

You're creating a dependency on the file name / location with this kind of code. What happens if the sever admin moves the images folder? Or if you misspell a movie title when calling the function?

This kind of situation us normally better suited for server code to generate based on a data source of actual movie information (including file name and location).

Upvotes: 0

underscorePez
underscorePez

Reputation: 897

Simple:

function movieCreator(movieName){
      alert(movieName);
}

movieCreator('terminator');
movieCreator('rambo');

Upvotes: 0

Furqan Hameedi
Furqan Hameedi

Reputation: 4400

Try this

      function movieCreator(movieName){
         var imgTag= '<img class="clip '+ movieName +'" src="images/'+ movieName + '.png" onclick="imageControl(this);" alt="'+ movieName+'" />'

      };

Upvotes: 0

Charlie
Charlie

Reputation: 1332

    function movieCreator(movieName) {
        return '<img class="clip ' + movieName + '" src="images/' + movieName + '.png" onclick="imageControl(this);" alt="' + movieName + '" />';
    };
    movieCreator('terminator');
    movieCreator('rambo');

Upvotes: 0

Glen Hughes
Glen Hughes

Reputation: 4832

Something like this?

'<img class="clip ' + movieName + '" src="images/' + movieName + '.png" onclick="imageControl(this);" alt="' + movieName + '" />'

Upvotes: 0

bugwheels94
bugwheels94

Reputation: 31950

Call function like

movieCreator('terminator');
movieCreator('rambo');

Create function like

function movieCreator(movieName){

'<img class="clip '+movieName+'" src="images/'+movieName+'.png" onclick="imageControl(this);" alt="'+movieName+'" />','

};

Upvotes: 1

Related Questions