Execute command with variable -JS

Asked

Viewed 989 times

2

Good morning ,

On a page, I have some div to which I put an effect for them to appear (toogle) I would like that effect to be alternated whenever I perform its respective function.

Then, I discovered this function that scrambles the contents of an array

function embaralhar_efeito(o){
        for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o[0]; //retorna somente o 1 valor.
    }

    var array_efeitos = ['slideToggle','slideDown','slideUp','fadeToggle','fadeTo','fadeIn'];
    var efeito_toogle = embaralhar_efeito(array_efeitos);

So , I pass the result to the function that would toogle in my div:

function efeito_pergunta(efeito){

        var modifica = '$("#div_pergunta").';
        var modifica_2 = efeito+'(3000);';

        var acao = modifica + modifica_2;
    }

When do an Alert(action) it returns $("#div_question"). slideDown(3000);//here , the effect(slideDown) changes as it performs the scramble_effect function. But the div doesn’t get the toogle effect.

You have to execute the code this way ?

From now on, grateful

3 answers

3

You can use [] to access properties and methods of an object from the value of a variable.

function efeito_pergunta(efeito) {
   $('#div_pergunta')[efeito](300);
}

See here an example working

1

Try the following on:

function efeito_pergunta(efeito){
    var modifica = '$("#div_pergunta").';
    var modifica_2 = efeito+'(3000);';
    var acao = modifica + modifica_2;
    eval(acao);
}

1


Instead of turning every jquery method into a string and saving it into a variable you can run straight by just passing as a property of an object:

function embaralhar_efeito(o) {
  for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o[0]; //retorna somente o 1 valor.
}
var array_efeitos = ['slideToggle', 'slideDown', 'slideUp', 'fadeToggle', 'fadeTo', 'fadeIn'];
var efeito_toogle = embaralhar_efeito(array_efeitos);
efeito_pergunta(efeito_toogle);

function efeito_pergunta(efeito) {
  $("#div_pergunta")[efeito]('3000');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="div_pergunta">Conteudo aqui</div>

  • Good afternoon , thank you , gave right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.