0

I have functions called

BeforeSlide1() {
...
}


BeforeSlide2() {
...
}

And I would like to be able to build the call to these dynamically in a loop, something like this:

        code = "BeforeSlide" + slide + "()"
        eval(code); 

Now this code of mine obviously doesn't work (if only it was that simple!) anyone know?

All right, I'll draw up the big picture.

I have a slideshow run by a simple script

    function slideshow(slide) {
            if (pauseTimes[slide]>0) {
                    /* if there is another slide after the one currently showing... */

                //Call BeforeSlide-function if there is one
                code = "BeforeSlide" + slide + "();"
                try {
                    eval(code);                 

                } catch(e) {
                    /* do nothing since many slides don't have one */
                }           
                $('#slide'+slide).
                fadeIn(1500,function(){}).
                delay(pauseTimes[slide]).
                fadeOut(1500,function(){slideshow(slide+1);});
                ;
            }
            else {
                    /* if there is no more slide and we've reached the end, try to ajax-refresh the slideshow contents */
                ajaxUpdate();
            }
            }

Among the HTML of the slides themselves, the before- and afterfunctions are defined like this:

    /* fire the slideshow from slide 1 once document is finished loading */
    $(document).ready(function(){
        slideshow(1);
    });

    </script>

    </HEAD>

    <body id="slideshow_body">

    <script id='pauseTimesScript' type='text/javascript'>
    /* Define pauseTimes (array holding duration of each slide) */
    try {
            pauseTimes=null;
            pauseTimes=undefined;
            pauseTimes = new Array();   
            setPauseTimes();        
            /*alert('satte först till null, deklarerade sedan om.');*/
    } catch(e) {
            pauseTimes = new Array();   
            setPauseTimes();        
            /*alert('deklarerade utan att först sätta null.');*/
    }

    function setPauseTimes() {  

        pauseTimes[1]=2000;         

        pauseTimes[2]=2000;         

        pauseTimes[3]=2000;         

    }
    </script>

    <div id="avbrott">Tillfälligt avbrott, visar cachelagrat innehåll sedan 2012-10-31 16:37:35</div>

    <div id="canvas" style="width:1072px;height:732px;">

                <script language='text/javascript'>
                function BeforeSlide1(order=1) {
                alert('here goes slide '+order);

                }
                </script>
                        <div id="slide1" class="slide" style="z-index:1;">



    <div id="slide_bg" style="float:left;height:100%;width:100%;background-color:#ffffff;background-image:url('http://bglabs.evade.netdna-cdn.com/45875kli90/505.jpg');">

        <div style="background-color:#eeeeee;color:#000000;float:right;text-align:center;margin-top:30px;padding:10px;font-weight:bold;font-size:30pt;" id="preview_title">Egypt rocks!</div>
        <div style="clear:both;float:none;"></div>

        <p style="color:#000000;margin:10px 10px 0 20px;font-style:italic;font-size:38pt;" id="preview_data_6">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat pharetra eros, vitae ullamcorper tellus condimentum sit amet. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Suspendisse in leo erat. Aliquam interdum molestie tortor, nec lacinia mauris viverra eget. Suspendisse aliquam tempor scelerisque. Proin vel purus nunc. Pellentesque ut sapien libero.<br />
    </p>

    </div>

The purpose of this BeforeSlide function is of course to do other stuff than produce an alert...

Please let me know how I should structure it in a better way! =)

2
  • 1
    If you need to write code like this, you're almost certainly doing something wrong. Oct 31, 2012 at 15:34
  • 3
    This could be done, but if you explain the real problem, there is probably a much, much better way to solve it.
    – jfriend00
    Oct 31, 2012 at 15:34

3 Answers 3

2

Don't use eval! Every function declared will be available through the window. Try this:

function test() {
    alert("test");
}

var x = window['test'];
x();

Example fiddle

However, it would be much more logical to have a single function and to pass the integer as a parameter to that.

3
  • Can't do that since the slideshow is made up of slides from different "templates", some templates will have these before functions and some won't, and they are rendered together with the slide... Oct 31, 2012 at 15:42
  • It works on fiddle, but when I do it in my code I get a console error "Uncaught TypeError: undefined is not a function" (I moved the call out of the try block to see what happens) Oct 31, 2012 at 15:55
  • You had the settings for the fiddle wrong. For this to work you need to use no wrap (head): jsfiddle.net/eZK4j/1 Nov 4, 2012 at 18:42
1

I would probably create an object like below,

var myFunc = {
    BeforeSlide1: function () {
        //some stuff
    },
    BeforeSlide2: function () {
        //some stuff
    } 
}

And then you can simply call myFunc['BeforeSlide' + num]

0
0
var code = "this.f = BeforeSlide" + slide + "() {...}";
eval(code);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.