www.webdeveloper.com
Results 1 to 5 of 5

Thread: Need assistance with repeated code.

  1. #1
    Join Date
    Apr 2014
    Posts
    2

    Need assistance with repeated code.

    I have the following code repeated in 3 different places:

    var el = document.getElementById("mydiv");
    el.innerHTML=caption[i];
    var img= document.getElementById("slide");
    img.src= image[i];

    I'm wanting to take the above code, move it into a function such as setCaption() and setImage(), and call those functions where I have the repeated code. Need help with what this should look like

    Thanks

  2. #2
    Join Date
    Aug 2008
    Posts
    40
    Probably going to need to provide a little more information than this. What the rest of the code looks like, what the end result should be, etc.,.

    . . .

  3. #3
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843
    i would suggest something like
    Code:
    function setCaption(text)
    {
        var obj = document.getElementById('mydiv');
    
        if(obj) {
            obj.innerHTML = text;
        }
    }
    function setImage(url)
    {
        var obj = document.getElementById('slide');
    
        if(obj) {
            obj.src= url;
        }
    }
    function setImageCaption(url, text)
    {
        setImage(url);
        setCaption(text);
    }
    this allow you to call both functions in one go, or the option to call them independently. if you don't need the independent usage you can do like
    Code:
    function setImageCaption(url, text)
    {
        var el = document.getElementById('mydiv');
        var im = document.getElementById('slide');
    
        if(el && im) {
            el.innerHTML = text;
            im.src = ulr;
        }
    }
    function statement
    function expression

  4. #4
    Join Date
    Aug 2008
    Posts
    40
    Missed that one. . . There you go, learn something every day.

    . . .

  5. #5
    Join Date
    Apr 2014
    Posts
    2
    Thank you. I was able to use your suggestion for calling each function and incorporate this into my code.

    Problem Solved

    hip2christ

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles