Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

javascript - Click a button programmatically - JS

I've seen this done in other webapps, but I'm fairly new to Javascript and can't really figure this out on my own. I want to create a Google Hangout programmatically. However, in the official API the only way you can create a Hangout is by including the Hangout button on your page.

Here's the Google doc on the Hangouts button.

What I want to do is have a user click an img of another user and open the Hangout this way. It seems like I could capture that click and then 'click' the Hangouts button in the background. However, I'm not very good with Javascript so I wouldn't know how to achieve this.

EDIT

I tried mohamedrais' solution below with no luck. Is it something to do with the class of the button?

Here's the code for the button, taken from the Hangouts docs with an added id:

 <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script>
        <div class="g-hangout" id="hangout-giLkojRpuK"
                                data-render="createhangout">
        </div>

Here's the JS I added, rendered with ids:

     <script>
          window.onload = function() {

              var userImage = document.getElementById("img-giLkojRpuK");
              var hangoutButton = document.getElementById("hangout-giLkojRpuK");

              userImage.onclick = function() {

                console.log("in onclick");
                hangoutButton.click(); // this will trigger the click event
              };
          };
        </script>

When I click the img, "in onclick" is getting logged, so the function is getting called. However, nothing happens - Hangouts isn't launched.

When I do click directly on the Hangouts button it does launch Hangouts. However, I want to eventually hide this and perform the click from the image.

Here's a picture of the Hangouts button above the img:

enter image description here

question from:https://stackoverflow.com/questions/24278469/click-a-button-programmatically-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {
       hangoutButton.click(); // this will trigger the click event
    };
};

this will do the trick


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...