mardi 8 septembre 2015

How do I assure the visibility of at least one element when randomly calling a function with javascript?

I have a function to randomly select the visibilty of an html element by its id. I call the function two time on one elements, hence it may appear, that both elements are invisible. I want to avoid having none of both display. I've tried it with a separate function and also by modifying my random function. Here is my code:

            function turn_visible(id) {
                var e = document.getElementById(id);
                if (e.style.display == 'hidden')
                e.style.display = 'block'; else
                e.style.display = 'block';
            }

            function in_visible(id) {
                var e = document.getElementById(id);
                if (e.style.display == 'block')
                e.style.display = 'none'; else
                e.style.display = 'none';
            }

            function random_vis(id, id) {
                var func = randomFrom([turn_visible, in_visible]);
                (func)(id);
            }

           function randomFrom(array) {
              return array[Math.floor(Math.random() * array.length)];
            }                

Here is how I try to check the visibility:

            function check_visible(id1, id2) {
                var e1 = document.getElementById(id1);
                var e2 = document.getElementById(id2);              
                if ((e1.style.display == 'hidden'),(e2.style.display == 'hidden')){                             
                var func = randomFrom([turn_visible(id1), in_visible(id2)]);
                (func)(id1, id2);}
                     }

This is how I use the function in the html markup:

    <a href="#page1" onclick="random_vis('rap-1812-1'); 
                              random_vis('rap-1857-1');
                              check_visible('rap-1812-1','rap-1857-1')">
    </a>        




Aucun commentaire:

Enregistrer un commentaire