• Login
sketchucation logo sketchucation
  • Login
🤑 SketchPlus 1.3 | 44 Tools for $15 until June 20th Buy Now

Trouble triggering javascript event from sketchup

Scheduled Pinned Locked Moved Developers' Forum
14 Posts 4 Posters 681 Views 4 Watching
Loading More Posts
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    cjthompson
    last edited by cjthompson 9 Mar 2010, 18:05

    I am trying to create a dynamic web page through javascript. Everything is working except for the "onclick" event for buttons.

    here is an example of what I'm doing:

    
    class WebTest
    	@@webDialog = UI;;WebDialog.new("This is a test",true,"Test",250,250,250,250,true)
    	html ="
    		<html>
    		<head>
    			<script>
    			function addButton()
    			{
    				body = document.body;
    				button = document.createElement('input');
    				button.type = 'button';
    				button.value = 'Click Me';
    				var message = 'I am working';
    				button.onclick = 'alert(message);';
    				button.id = 'btn1';
    				body.appendChild(button);
    			}
    			</script>
    		</head>
    		<body>
    		</body>
    		</html>"
    	@@webDialog.set_html(html)
    	def initialize
    		@@webDialog.show
    	end
    	def self.addButton
    		@@webDialog.execute_script("addButton()")
    	end
    end
    
    

    to test it, copy and paste the following code into an .rb, and type WebTest.new, then WebTest.addButton into the console.

    It doesn't work in the sketchup webdialog, but when I copy and paste the same code into a regular browser, it does:

    javascript&#058;body = document.getElementsByTagName('body')[0];button = document.createElement('input');button.setAttribute('type','button');button.setAttribute('id','btn1');button.setAttribute('value','Click Me');var message = 'I am working';button.setAttribute('onclick','alert(message)');body.appendChild(button);
    

    does anyone have any ideas?

    1 Reply Last reply Reply Quote 0
    • M Offline
      MartinRinehart
      last edited by 9 Mar 2010, 20:26

      Some random notes. I bet one of these (no idea which!) fixes the issue.

      1. "document.body" works. No need to look it up.
      2. "setAttribute" has issues. Easier to say "button.id = 'btn1';"
      3. The WebDialog parameters are wrong in the doc. Never tried to use just one. Try (title, scrollable, registryKey, width, height, left, top, resizable). (Set scrollable true. It will always be true on a PC, regardless of this param's value.)
      4. There are timing issues calling execute_script. Put a button in a minimal WD. Click the button to call a Ruby action_callback. execute_script() in the action_callback. (I named this The Bug from Hell. It took me nearly a week to find this out. If you execute_script() before your page is correctly formed, it won't work and you'll get no error. Ugh.)
      5. Style points: This might all be more readable laid out as a Ruby multiline string:
        html = <<eos

      <html> <body>
      <script type='text/javascript'>
      function make_button() {
      button = document.createElement('input');
      button.attr = value;
      button.other_attr = other_value;
      ...
      document.body.appendChild( button )
      }
      </script> </body> </html>

      eos

      @@webDialog.set_html( html )

      Come to think of it, I'm betting on #4.

      Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

      1 Reply Last reply Reply Quote 0
      • C Offline
        cjthompson
        last edited by 9 Mar 2010, 21:35

        I've edited the top post to reflect the changes you suggested.

        It is showing the exact same behaviour, it adds the button properly, but doesn't trigger.

        1 Reply Last reply Reply Quote 0
        • T Offline
          thomthom
          last edited by 9 Mar 2010, 22:06

          @unknownuser said:

          button.onclick = 'alert(message);';

          You are assigning a string to the event.

          button.onclick = function() { alert(message); };

          Maybe you can skip the function wrapper when you only do one method call - can't remember right now.
          button.onclick = alert(message);

          Thomas Thomassen — SketchUp Monkey & Coding addict
          List of my plugins and link to the CookieWare fund

          1 Reply Last reply Reply Quote 0
          • T Offline
            thomthom
            last edited by 9 Mar 2010, 22:08

            hmm... turns out that the string thing is a legacy way of doing it.

            I think that you need to append the element and then attach events.

            Thomas Thomassen — SketchUp Monkey & Coding addict
            List of my plugins and link to the CookieWare fund

            1 Reply Last reply Reply Quote 0
            • T Offline
              todd burch
              last edited by 10 Mar 2010, 03:15

              @cjthompson said:

              I am trying to create a dynamic web page through javascript. Everything is working except for the "onclick" event for buttons.
              ...

              does anyone have any ideas?

              Yes. This works on a Mac: (Didn't test on IE)

              
              class WebTest < UI;;WebDialog  
              
              	def initialize 
              		super("This is a test",true,"Test",250,250,250,250,true) ;
              		html =<<HTML
              <html>
              <head>
              <script>
              function addButton() {
              	alert('hi there'); 
              	var body = document.body;
              	var button = document.createElement('input');
              	button.type = 'button';
              	button.value = 'Click Me';
              	button.id = 'btn1';
              	var message = 'I am working';
              	button.addEventListener("click", function() { alert(message);} , true ) ; 
              	body.appendChild(button);
              }
              </script>
              </head>
              <body> 
              Yo
              </body>
              </html>
              HTML
              		set_html(html)
              		end
              
              		def add_button 
              			execute_script("addButton();") ; 
              		end ; 
              
              end
              

              And, in the Ruby Console:

              
              > load 'myscripts/webtest.rb'
              true
              > w = WebTest.new
              #<WebTest;0x1d545b24>
              > w.show
              true
              > w.add_button
              true
              
              
              1 Reply Last reply Reply Quote 0
              • M Offline
                MartinRinehart
                last edited by 10 Mar 2010, 13:14

                @cjthompson said:

                I've edited the top post to reflect the changes you suggested.

                Well, that sure is easier to read. To make it work, try my fourth suggestion. Have preliminary JS put up a big button that says "Start!" or whatever. That button's onclick() calls an action_callback in the Ruby. The action_callback can safely execute_script().

                Another thing I see is the onclick() timing. The click will happen sometime after addButton() has run to completion. message will no longer exist. Move var message = ... outside the function. (No, you really don't have to worry about polluting the global namespace in a WebDialog.)

                Pay attention to thomthom's remarks re attaching code to the event handler.

                Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                1 Reply Last reply Reply Quote 0
                • C Offline
                  cjthompson
                  last edited by 10 Mar 2010, 13:18

                  @unknownuser said:

                  This works on a Mac: (Didn't test on IE)

                  For some reason, the alert box is popping up automatically, without adding the button.

                  However, this did work for me:

                  @thomthom said:

                  button.onclick = function() { alert(message); };

                  @thomthom said:

                  hmm... turns out that the string thing is a legacy way of doing it.

                  Yeah, I'm not the best keeping up with standards. 😳

                  Anyways, I think that will do it for me. Thanks everyone for the replies.

                  1 Reply Last reply Reply Quote 0
                  • T Offline
                    todd burch
                    last edited by 10 Mar 2010, 14:30

                    Is the alert box that is popping up this one?

                    
                    alert('hi there'); 
                    
                    

                    ?

                    1 Reply Last reply Reply Quote 0
                    • C Offline
                      cjthompson
                      last edited by 10 Mar 2010, 15:42

                      ah, I completely missed that. Yes it is.

                      I'm getting an error "Object doesn't support this property or method." on this line:

                      button.addEventListener("click", function() { alert(message);} , true ) ;
                      

                      Is anyone else with IE getting this?

                      1 Reply Last reply Reply Quote 0
                      • T Offline
                        thomthom
                        last edited by 10 Mar 2010, 16:20

                        what IE do you got? thing IE might have its own way to attach events...

                        Javascript - Introduction to Events

                        favicon

                        (www.quirksmode.org)

                        Thomas Thomassen — SketchUp Monkey & Coding addict
                        List of my plugins and link to the CookieWare fund

                        1 Reply Last reply Reply Quote 0
                        • M Offline
                          MartinRinehart
                          last edited by 10 Mar 2010, 16:51

                          Javascript - Advanced event registration models

                          favicon

                          (www.quirksmode.org)

                          ppk's conclusion: don't use addEventListener if you need to support MSIE.

                          Author, Edges to Rubies - The Complete SketchUp Tutorial at http://www.MartinRinehart.com/models/tutorial.

                          1 Reply Last reply Reply Quote 0
                          • T Offline
                            todd burch
                            last edited by 10 Mar 2010, 17:36

                            Like I said, not tested on IE. If the browser does not respond to button.addEventListener, use button.attachEvent.

                            https://developer.mozilla.org/en/DOM/element.addEventListener

                            (By the way, I spent > 2 hours on this last night)

                            1 Reply Last reply Reply Quote 0
                            • T Offline
                              thomthom
                              last edited by 10 Mar 2010, 17:45

                              @unknownuser said:

                              button.attachEvent.

                              Yes -that jogged my memory - attachEvent was the IE way. (imagined that later IE (IE7 or IE8) used addEventListener as it's part of the DOM standard. But maybe I was wrong. ...or maybe it depends on the doctype....

                              Thomas Thomassen — SketchUp Monkey & Coding addict
                              List of my plugins and link to the CookieWare fund

                              1 Reply Last reply Reply Quote 0
                              • 1 / 1
                              1 / 1
                              • First post
                                1/14
                                Last post
                              Buy SketchPlus
                              Buy SUbD
                              Buy WrapR
                              Buy eBook
                              Buy Modelur
                              Buy Vertex Tools
                              Buy SketchCuisine
                              Buy FormFonts

                              Advertisement