Web Analytics Made Easy -
StatCounter Script executing before it should... - CodingForum

Announcement

Collapse
No announcement yet.

Script executing before it should...

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Script executing before it should...

    See the code below, the alert is displayed when the page is loaded. It should only display when the image is moused over...

    Code:
    <script type="text/javascript">
    addEvent(document.getElementById('snake'), "mouseover", fadeByid(this));
    
    //This function attaches events to elements. 
    function addEvent( elm, evt, fun ) {
    	if ( elm.addEventListener ) {
    		elm.addEventListener( evt, fun, false );
    	} else if ( elm.attachEvent ) {
    		elm.attachEvent( 'on' + evt, fun );
    	} else {
    		elm [ 'on' + evt ] = fun;
    	}
    };
    
    //Image fade, for the main front navigation
    function fadeByid(objId) {
    	alert("wtf");
    	if (document.getElementById) {
    		obj = document.getElementById(objId);
    		opacity = obj.style.opacity;
    		alert(opacity);
    		if (opacity >= 100) {
    			setOpacity(obj, opacity);
    			opacity -= 10;
    			window.setTimeout("fadeByid('"+objID+"','"+opacity+")", 100);
    		}
    	}
    }
    What's wrong with it? :/

  • #2
    fadeByid(this) is wrong. The second parameter for addEventListener and attachEvent is supposed to be a function object but instead your third parameter is the result of the function call (and the result is not a function object).

    Try this
    Code:
    addEvent(document.getElementById('snake'), "mouseover", fadeByid);
    Next you are expecting an id attribute of an element as the first parameter of fadeByid ... but this will not happen. But nevertheless, the clicked image will be available inside the function as "this".

    Comment


    • #3
      This is how i would handle the mouseover part.
      We can talk about the fade part seperatly
      if you like.

      Code:
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
      <html lang="en">
      <head>
      <meta http-equiv="content-type" content="text/html; charset=utf-8">
      <meta name="generator" content="daveyerwin">
      <title>Untitled</title>
      <head>
      <script type="text/javascript">
      function init(){
      addEvent(document.getElementById('snake'), "mouseover", handleMouseOver);}
      
      addEvent(window,"load",init);
      
      //This function attaches events to elements. 
      function addEvent( elm, evt, fun ) {
      	if ( elm.addEventListener ) {
      		elm.addEventListener( evt, fun, false );
      	} else if ( elm.attachEvent ) {
      		elm.attachEvent( 'on' + evt, fun );
      	} 
      };
      
      function handleMouseOver(e) {	
      	alert('n')
      	/* call fade function */
      }
      
      </script>
      <style type="text/css">
      div{width:5em;background-color:red;}
      </style>
      </head>
      <body>
      
      <div id="snake">xx</div>
      
      </body>
      </html>

      Comment


      • #4
        Ah, I think that is the way I used to do it. Not done any coding for a long time, forgot a lot lol. Thanks

        Although, the alert is bringing up "undefined":
        Code:
        function init() {
        	addEvent(document.getElementById('snake'), "mouseover", fadeByid);
        }
        //Attach listeners on page load, must be below listener calls. 
        addEvent(window,"load",init);
        
        //This function attaches events to elements. 
        function addEvent( elm, evt, fun ) {
        	if ( elm.addEventListener ) {
        		elm.addEventListener( evt, fun, false );
        	} else if ( elm.attachEvent ) {
        		elm.attachEvent( 'on' + evt, fun );
        	} else {
        		elm [ 'on' + evt ] = fun;
        	}
        };
        
        //Image fade, for the main front navigation
        function fadeByid(obj) {
        	alert(obj.id);
        	if (document.getElementById) {
        		element = document.getElementById(obj);
        		opacity = element.style.opacity;
        		alert(opacity);
        		if (opacity >= 100) {
        			setOpacity(element, opacity);
        			opacity -= 10;
        			window.setTimeout("fadeByid('"+obj+"','"+opacity+")", 100);
        		}
        	}
        }
        Is obj.id the correct way to get the ID value? (getting the ID value purely to make sure it's fetching it)

        Comment


        • #5
          Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
          <html lang="en">
          <head>
          <meta http-equiv="content-type" content="text/html; charset=utf-8">
          <meta name="generator" content="daveyerwin">
          <title>Untitled</title>
          <head>
          <script type="text/javascript">
          function init(){
          addEvent(document.getElementById('snake'), "mouseover", handleMouseOver);}
          
          addEvent(window,"load",init);
          
          //This function attaches events to elements. 
          function addEvent( elm, evt, fun ) {
          	if ( elm.addEventListener ) {
          		elm.addEventListener( evt, fun, false );
          	} else if ( elm.attachEvent ) {
          		elm.attachEvent( 'on' + evt, fun );
          	} 
          };
          
          function handleMouseOver(e) {	     
          	e = e || event;
                  target = e.target || e.srcElement;
                  alert(target.id);
          	fadeFunc(target)
          }
          
          function fadeFunc(){
             function inner(){
             setTimeout(inner,500)
             }
          }

          Comment


          • #6
            This May not be what you want ?
            My compulsive disorder forces
            mr to post it. Thanks to any who
            review and comment.

            Code:
            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
            <html lang="en">
            <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8">
            <meta name="generator" content="daveyerwin">
            <title>Untitled</title>
            <head>
            <script type="text/javascript">
            function init(){
            addEvent(document.getElementById('snake'), "mouseover", handleMouseOver);}
            
            addEvent(window,"load",init);
            
            //This function attaches events to elements. 
            function addEvent( elm, evt, fun ) {
            	if ( elm.addEventListener ) {
            		elm.addEventListener( evt, fun, false );
            	} else if ( elm.attachEvent ) {
            		elm.attachEvent( 'on' + evt, fun );
            	} 
            };
            
            function handleMouseOver(e) {	     
            	e = e || event;
                    target = e.target || e.srcElement;
            	fadeFunc(target);
            }
            var flag = null;
            function fadeFunc(target){
               if(flag)return;
               flag = true;   
               var opacityLevel = 100;
               (function inner(){
            	target.style.opacity = opacityLevel / 100;
            	target.style.filter = 'alpha(opacity='+opacityLevel+')';
               	if(opacityLevel--){
            	    setTimeout(inner,5);
            	   }else{
            	    flag = null;
            	   }
            })()
               
            }
            
            </script>
            <style type="text/css">
            </style>
            </head>
            <body>
            
            <img id="snake" src="test.jpg">xx</img>
            
            </body>
            </html>
            Last edited by DaveyErwin; Sep 8, 2011, 02:34 PM.

            Comment


            • #7
              May I ask why the function is wrapped with () ?

              And what is the "flag" doing? I'm guessing "flag" is a reserved word for JS?

              Comment


              • #8
                Originally posted by martynball View Post
                May I ask why the function is wrapped with () ?

                And what is the "flag" doing? I'm guessing "flag" is a reserved word for JS?
                No not a keyword just a variable, I should have
                named it isFading. While the opacityLevel
                is not zero flag is true which prevents another
                mouse over from restarting the fade process.
                When opacityLevel is deincremented to zero
                is timer is not set again and flag is nulled
                to allow the next mouseover to set
                opacityLevel to 100 again and start
                the fade process over.


                var isFading = null;
                function fadeFunc(target){
                if(isFading)return;
                isFading = true;
                var opacityLevel = 100;
                (function inner(){
                target.style.opacity = opacityLevel / 100;
                target.style.filter = 'alpha(opacity='+opacityLevel+')';
                if(opacityLevel--){
                setTimeout(inner,5);
                }else{
                isFading = null;
                }
                })()
                }

                function (){alert("I won't alert")}

                the above function won't alert
                because it can't be called .

                (function (){alert("I call myself")})()

                by wrapping in eclipses and adding
                eclipses after, the function is called.

                so this code


                Code:
                (function inner(){
                	target.style.opacity = opacityLevel / 100;
                	target.style.filter = 'alpha(opacity='+opacityLevel+')';
                   	if(opacityLevel--){
                	    setTimeout(inner,5);
                	   }else{
                	    isFading = null;
                	   }
                     })()
                is the same as


                Code:
                function inner(){
                	target.style.opacity = opacityLevel / 100;
                	target.style.filter = 'alpha(opacity='+opacityLevel+')';
                   	if(opacityLevel--){
                	    setTimeout(inner,5);
                	   }else{
                	    isFading = null;
                	   }
                     }
                inner()
                Instead of inner, I should have named it fader.

                Comment


                • #9
                  Another question, what is the purpose of the 2 lines below?

                  Code:
                  e = e || event; 
                  obj = e.target || e.srcElement;
                  Can't I just use "e" normally? For example alert(e). or is the redefining of the variable for cross browsing?

                  Also, what is the e.target for and srcElement? Does that see what element activated the event?

                  Comment


                  • #10
                    Originally posted by martynball View Post
                    Another question, what is the purpose of the 2 lines below?

                    Code:
                    e = e || event; 
                    obj = e.target || e.srcElement;
                    Can't I just use "e" normally? For example alert(e). or is the redefining of the variable for cross browsing?

                    Also, what is the e.target for and srcElement? Does that see what element activated the event?
                    Yes,
                    e = e || event;
                    is not necessary
                    try the code below


                    Code:
                    function handleMouseOver(e) {
                            //e = e || event; 
                    alert(e)
                            obj = e.target || e.srcElement;	
                    alert(obj)
                    	fadeFunc(obj);
                    }
                    the fisr alert shows
                    object event
                    the second shows
                    HTML Object imageElement
                    that is the element refference
                    to the image that was clicked on

                    This is a lot better code here ...

                    Code:
                    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                    <html lang="en">
                    <head>
                    <meta http-equiv="content-type" content="text/html; charset=utf-8">
                    <meta name="generator" content="daveyerwin">
                    <title>Untitled</title>
                    <head>
                    <script type="text/javascript">
                    function init(){
                    addEvent(document.getElementById('snake'), "mouseover", fadeFunc);}
                    
                    addEvent(window,"load",init);
                    
                    //This function attaches events to elements. 
                    function addEvent( elm, evt, fun ) {
                    	if ( elm.addEventListener ) {
                    		elm.addEventListener( evt, fun, false );
                    	} else if ( elm.attachEvent ) {
                    		elm.attachEvent( 'on' + evt, fun );
                    	} 
                    };
                    
                    
                    var flag = null;
                    function fadeFunc(e){
                       var target = e.target || e.srcElement;
                       if(flag)return;
                       flag = true;   
                       var opacityLevel = 100;
                       (function inner(){
                    	target.style.opacity = opacityLevel / 100;
                    	target.style.filter = 'alpha(opacity='+opacityLevel+')';
                       	if(opacityLevel--){
                    	    setTimeout(inner,5);
                    	   }else{
                    	    flag = null;
                    	   }
                    })()
                       
                    }
                    
                    </script>
                    <style type="text/css">
                    </style>
                    </head>
                    <body>
                    
                    <img id="snake" src="test.jpg">xx</img>
                    
                    </body>
                    </html>
                    Last edited by DaveyErwin; Sep 15, 2011, 03:06 PM.

                    Comment


                    • #11
                      Yes,
                      e = e || event;
                      is not necessary
                      try the code below
                      But depending on the browser, the code below will not work without the e = e || event

                      At least in older IE there won't be any argument handed over to the event handler but instead you'd have to use the global "event" object (window.event).

                      Comment


                      • #12
                        Okay thanks, another question. How would I use the "e" value which returns "[object MouseEvent]" to detect if it was a mouseover or mouseout?

                        Comment


                        • #13
                          There ya go ...

                          Code:
                          function fadeFunc(e){
                          alert(e.type)
                             var target = e.target || e.srcElement;}
                          but going back to the first way
                          I posted with eventHandler
                          Code:
                          function handleMouseOver(e) {	     
                          	e = e || event;
                                  target = e.target || e.srcElement;
                          	fadeFunc(target);
                          }

                          you already know the event.
                          And since
                          e = e || event;
                          doen't hurt , why not leave it
                          in for "old time's sake"
                          Last edited by DaveyErwin; Sep 15, 2011, 05:55 PM.

                          Comment


                          • #14
                            Should of guessed it would be something simple like .type lmao.

                            And I will leave it in then thanks. Also, Firefox seems to use "opacity: 0.5" for 50% opacity, but none of the styles on the JS you posted would change it to these. Is this okay?

                            Comment


                            • #15
                              target.style.opacity = opacityLevel / 100;
                              is for is
                              target.style.filter = 'alpha(opacity='+opacityLevel+')';
                              is for firefox
                              If you were inclined to be
                              pedantic you would determine through
                              feature testing which one was currently
                              in use and execute only yhe correct one.
                              By using both of them as i have the
                              browsers will issue warnings but
                              not errors.

                              Comment

                              Working...
                              X
                              😀
                              🥰
                              🤢
                              😎
                              😡
                              👍
                              👎