Ir para conteúdo
mzaidan

Clicar no botão automaticamente

Recommended Posts

Prezados, existe alguma função que quando a pessoa entre em uma pagina um <button> seja clicado automaticamente???

 

<div class="col px-0">
                        <button id="by-link" type="button" class="btn btn-info">Enviar</button>
                        
 </div>

Grato

Compartilhar este post


Link para o post
Compartilhar em outros sites

Obrigado pela resposta.

Tentei aqui, mas não deu certo.

Segue o código:

<!DOCTYPE htm>
<html lang="en-US"><head>
<head>
    <title>WathsApp Send</title>
    <meta charset="utf-8">
    <meta name="description" content="Send WhatsApp Message !">
    <meta name="keywords" content="fragments, paste, codes, demos, javascript, css, lab">
    <meta name="author" content="Subversivo58">
    <link type="image/png" rel="shortcut icon" href="./labicon.png">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>

    <!-- CONTAINER -->
    <section class="container-fluid px-0 pt-5">

        <div class="col col-sm-8 col-md-5 col-lg-4 mx-auto px-0 mb-5">
            <form accept-charset="utf-8">
                <div class="form-group mb-2">
                    
                    <div class="input-group">
                        <div class="input-group-prepend">
                            
                        </div>
                        <input id="phone" type="hidden" class="form-control rounded-0" value="numero"> // aqui vou puxar de um banco de dados
                    </div>
                </div>
                <div class="form-group mb-2">
                   
                    <div class="input-group">
                        <div class="input-group-prepend">
                            
                        </div>
                        <input id="message" type="hidden" class="form-control rounded-0" value="*Mensagem Automática* - Prezado xxx, nosso sistema verificou que uma fatura referente ao mês de agosto encontra-se em aberto. Por favor, regularize-a!">
                    </div>
                
                </div>
                <div class="form-group mb-2">
                    
                    <div class="col px-0">
                        <button id="by-link" type="button" class="btn btn-info">Enviar</button>
                        
                     </div>
                </div>
            </form>
        </div>
    </section>
    
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let phone = document.getElementById('phone')
        let message = document.getElementById('message')        

        // buttons
        let linkHandler = document.getElementById('by-link')
        let popUpHandler = document.getElementById('by-popup')        

        // font: https://detectmobilebrowsers.com
        let isMobile = (function(a) {
            if ( /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)) ) {
                return true
            } else {
                return false
            }
        })(navigator.userAgent || navigator.vendor || window.opera)


        const makeLink = function(mode) {        

            let mount = function() {
                if ( isMobile ) {
                    let target = `whatsapp://send?`
                    if ( !!phone && phone.value !== '' ) {
                        target += `phone=${encodeURIComponent(phone.value)}&`
                    }
                    if ( !!message && message.value !== '' ) {
                        target += `text=${encodeURIComponent(message.value)}`
                    }
                    return target
                } else {
                    let target = `https://api.whatsapp.com/send?`
                    if ( !!phone && phone.value !== '' ) {
                        target += `phone=${encodeURIComponent(phone.value)}&`
                    }
                    if ( !!message && message.value !== '' ) {
                        target += `text=${encodeURIComponent(message.value)}`
                    }
                    return target
                }
            
            }        

            let openLink = function() {
                let a = document.createElement('a')
                a.target = '_blank'
                a.href = mount()
                a.click()
                console.log('By Link')
            }        

            let openPopUp = function() {
                let h = 650,
                    w = 550,
                    l = Math.floor(((screen.availWidth || 1024) - w) / 2),
                    t = Math.floor(((screen.availHeight || 700) - h) / 2)
                // open popup
                let options = `height=600,width=550,top=${t},left=${l},location=0,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=0`
                let popup = window.open(mount(), 'self', options)
                if ( popup ) {
                    popup.focus()
                }
                console.log('By PopUp')
            }
            
            switch (mode) {
                case 'link':
                    openLink()
                break
                case 'popup':
                    openPopUp()
                break
            }
        } 

        // events handler(s)
        linkHandler.addEventListener('click', function(e) {
            makeLink('link')
        }, false)
        popUpHandler.addEventListener('click', function(e) {
            makeLink('popup')
        }, false)
    </script>
 <script>
 document.getElementById("by-link").click();
</script>

</body>
</html>

http://brunoparma.com.br/whatsapp/

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pra mim funciona corretamente:

abre o console do teu navegador (f12)

 

 

<!DOCTYPE htm>
<html lang="en-US"><head>
<head>
    <title>WathsApp Send</title>
    <meta charset="utf-8">
    <meta name="description" content="Send WhatsApp Message !">
    <meta name="keywords" content="fragments, paste, codes, demos, javascript, css, lab">
    <meta name="author" content="Subversivo58">
    <link type="image/png" rel="shortcut icon" href="./labicon.png">
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>

<script>
<script>
document.getElementById("by-link").addEventListener("load", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>
</script>
</head>
<body>

    <!-- CONTAINER -->
    <section class="container-fluid px-0 pt-5">

        <div class="col col-sm-8 col-md-5 col-lg-4 mx-auto px-0 mb-5">
            <form accept-charset="utf-8">
                <div class="form-group mb-2">
                    
                    <div class="input-group">
                        <div class="input-group-prepend">
                            
                        </div>
                        <input id="phone" type="hidden" class="form-control rounded-0" value="numero"> // aqui vou puxar de um banco de dados
                    </div>
                </div>
                <div class="form-group mb-2">
                   
                    <div class="input-group">
                        <div class="input-group-prepend">
                            
                        </div>
                        <input id="message" type="hidden" class="form-control rounded-0" value="*Mensagem Autom�tica* - Prezado xxx, nosso sistema verificou que uma fatura referente ao m�s de agosto encontra-se em aberto. Por favor, regularize-a!">
                    </div>
                
                </div>
                <div class="form-group mb-2">
                    
                    <div class="col px-0">
                        <button id="by-link" type="button" class="btn btn-info">Enviar</button>
                        
                     </div>
                </div>
            </form>
        </div>
    </section>
    
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let phone = document.getElementById('phone')
        let message = document.getElementById('message')        

        // buttons
        let linkHandler = document.getElementById('by-link')
        let popUpHandler = document.getElementById('by-popup')        

        // font: https://detectmobilebrowsers.com
        let isMobile = (function(a) {
            if ( /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)) ) {
                return true
            } else {
                return false
            }
        })(navigator.userAgent || navigator.vendor || window.opera)


        const makeLink = function(mode) {   
        
        console.log('clique automático do botão! remove essa linha( document.getElementById("by-link").click();) e testa de novo');
        return false;

            let mount = function() {
                if ( isMobile ) {
                    let target = `whatsapp://send?`
                    if ( !!phone && phone.value !== '' ) {
                        target += `phone=${encodeURIComponent(phone.value)}&`
                    }
                    if ( !!message && message.value !== '' ) {
                        target += `text=${encodeURIComponent(message.value)}`
                    }
                    return target
                } else {
                    let target = `https://api.whatsapp.com/send?`
                    if ( !!phone && phone.value !== '' ) {
                        target += `phone=${encodeURIComponent(phone.value)}&`
                    }
                    if ( !!message && message.value !== '' ) {
                        target += `text=${encodeURIComponent(message.value)}`
                    }
                    return target
                }
            
            }        

            let openLink = function() {
                let a = document.createElement('a')
                a.target = '_blank'
                a.href = mount()
                a.click()
                console.log('By Link')
            }        

            let openPopUp = function() {
                let h = 650,
                    w = 550,
                    l = Math.floor(((screen.availWidth || 1024) - w) / 2),
                    t = Math.floor(((screen.availHeight || 700) - h) / 2)
                // open popup
                let options = `height=600,width=550,top=${t},left=${l},location=0,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=0`
                let popup = window.open(mount(), 'self', options)
                if ( popup ) {
                    popup.focus()
                }
                console.log('By PopUp')
            }
            
            switch (mode) {
                case 'link':
                    openLink()
                break
                case 'popup':
                    openPopUp()
                break
            }
        } 

        // events handler(s)
        linkHandler.addEventListener('click', function(e) {
            makeLink('link')
        }, false)
        popUpHandler.addEventListener('click', function(e) {
            makeLink('popup')
        }, false)
    </script>
 <script>
 document.getElementById("by-link").click();
</script>

</body>
</html>

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Acho que o meu não ta atualizando.
Quando peço para ver o codigo fonte, ainda ta o antigo.
Ja dei um ctrl + f5, mas ainda está o antigo.
O que tem o f12??

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por lezão
      Boa tarde, pessoal!
      Td bem com vcs?
       
      Estou a procura de um JS que me de retorno dos dados selecionados na pagina anterior.
      Eu escolho as minhas opções e qnd eu clicar em confirmar pedido chama outra pagina com os dados q eu selecionei mais os valor total
       
      Veja o código q estou utilizando:
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Documento sem título</title> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <style type="text/css"> #iconApiWhatsapp{ position: fixed; display: flex; right: 0px; bottom: 0px; z-index: 99999; right: 0px; position: fixed; width: 100%; bottom: 0px; background: rgba(0,0,0,0.8); height: 57px; text-align: center; } #iconApiWhatsapp img{ display: flex; align-items: center; justify-content: center; font-size: 24px; width: 150px; height: 57px; opacity: 0.5; filter: alpha(opacity=50); /* For IE8 and earlier */ -webkit-transition: opacity 0.5s; /* For Safari 3.1 to 6.0 */ transition: opacity 0.5s; } #iconApiWhatsapp img:hover{ opacity: 1; filter: alpha(opacity=100); /* For IE8 and earlier */ } </style> </head> <body> <table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="92%" align="left"><b>PORTUGUESA</b><br/> Molho de tomate, mussarela, calabresa ralada, catupiry, alho tostado, cebola, azeitonas e oregano.<br/><hr /></td> <td width="8%" align="center" valign="top"><b>28,00</b><br/> <input type="checkbox" name="sabor" id="evento_value2" value="28.00"> <input type="hidden" name="vl_sabor" value="28.00"> </td> </tr> <tr> <td align="left"><b>A MODA DA CASA</b><br/> Molho de tomate, mussarela, calabresa ralada, catupiry, alho tostado, cebola, azeitonas e oregano.<br/><hr /></td> <td align="center" valign="top"><b>28,00</b><br/> <input type="checkbox" name="sabor" id="evento_value2" value="28.00"> <input type="hidden" name="vl_sabor" value="28.00"></td> </tr> </table> <br/><br/><br/> <div id="iconApiWhatsapp" class="preco"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="15%" align="lef" onclick="location.href='finalizar_pedido.html'" style="cursor:pointer;"> <font size="5" color="yellow" face="aril tahoma verdana"> Confirmar Pedido</td> <td width="70%" align="center"> <font size="4" color="white" face="arial"><b><span id="resultado"></span></b> <!--Resultado da soma dos checkbox--> <!--Resultado Pegando a Variavel - Resultado checkbox --> </font> </td> <td width="15%" align="right"><a href="javascript:window.history.go(-1)"><<Voltar</a></td> </tr> </table> </div> <script type="text/javascript"> var total = 0; //Chama a função com click em qualquer checkbox $(":checkbox").click(function () { //Atribui o valor do input p/ variável 'valor' var valor = parseInt($(this).val()); //Se o checkbox for marcado ele soma se não subtrai if ($(this).is(":checked")) { total += valor; } else { total -= valor; } //Atribui o valor ao input $("#evento_value").val(total); $("#resultado").text(formatPrice(total)); }); function formatPrice(value, currency = true) { var valor = parseFloat(value); let valorFormatado = null; if(currency) { //Valor com cifrão valorFormatado = valor.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }); } else { //Valor sem cifrão valorFormatado = valor.toLocaleString('pt-BR', { minimumFractionDigits: 2}); } return valorFormatado; } </script> </body> </html>  
       
       
    • Por DOSDISDO
      Estou tentando alterar o evento onclick de butões gerados através do JavaScript. Por que meu código não funciona?   <p id='ai'>Click the button to make a BUTTON element with text.</p>
      <button onclick="generator()">Try it</button>
      <script>
      function generator() {
        for(var x=0; x<26; x++){
        var btn = document.createElement("BUTTON");
          btn.innerHTML=x;
          btn.onclick=function() {myFunction()};
        document.getElementById('ai').innerHTML+=btn.outerHTML;
        }
      }
      myFunction(){alert('bolas')};
    • Por Alberto Nascimento
      i("calcula").onclick = function(){ Este comando depois que eu atualizei meu servidor para PHP 7.2 não quer mais funcionar.
    • Por mamotinho
      Olá, boa noite! estou com bastante dificuldade em monta uma web com a versão do prototype e jquery.min pois eles são funções antigas e não estão compatíveis com as versões novas. gostaria de sabe se alguém conhece alguma forma nova de Utilizar onclick e ajax para abrir a página dentro da index sobre uma div ?
    • Por Airton Cruz
      Bom dia galera,
      Estou com uma situação que preciso resolver aqui na empresa. Tenho que abrir um popup a partir de botão, isso é facil, mas o botão faz parte de um formulário que precisa ser validado no momento do click do botão, ou seja, quando o usuário clicar no botão deve aparecer um POPup e validar o formulário de usuário e senha juntos.
       
      Segue o Codigo.
       
      -- criação da função do POPup
       
          <script language="javascript">
                          
                  function abrirPopup(url,w,h) {
                  var newW = w + 100;
                  var newH = h + 100;
                  var left = (screen.width-newW)/2;
                  var top = (screen.height-newH)/2;
                  var newwindow = window.open(url, 'name', 'width='+newW+',height='+newH+',left='+left+',top='+top);
                  newwindow.resizeTo(newW, newH);
                   
                  //posiciona o popup no centro da tela
                  newwindow.moveTo(left, top);
                  newwindow.focus();
                  return false;
                  }
          </script>
       
       <form name="formCliente" id="formCliente" action="http://www.google.com.br" method="post" class="clearfix" >
                          <input type="email" name="email" placeholder="E-mail:" value="" required="true"/>
                          <input type="password" name="senha" placeholder="Senha:" value="" required="true"/>
                         <button type="submit" class="bt-ok" onclick="return abrirPopup('popup2.html', 500, 270)">OK</button>
                          <div class="clear"></div>
                          <!--<div class="esqueci-minha-senha link-com-seta"><span></span><a href="/" title="Esqueci minha senha">esqueci minha senha</a></div>-->
                      </form>
       
       
      Por favor, preciso de ajuda urgente.
       
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.