Web Analytics Made Easy -
StatCounter Calling Style from Stylesheet Instead of Style Attribute - CodingForum

Announcement

Collapse
No announcement yet.

Calling Style from Stylesheet Instead of Style Attribute

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

  • Calling Style from Stylesheet Instead of Style Attribute

    A demo page with the code can be found here. I've created a fade-in on mouse-over effect.

    Problem: I'm trying to pass the image's current opacity to the script but this.style.opacity seems to only pass the value of the CSS opacity property if it's added to the image via the style attribute (style="opacity: 0.3;"). Since the image's opacity doesn't get passed, the script's mouse-over event resets the image to zero opacity instead of the correct starting opacity of 30%.

    Question: How do I pass the style from the stylesheet (from .opacity)?

  • #2
    This might help. http://www.javascriptkit.com/dhtmltu...cascade4.shtml
    ||||If you are getting paid to do a job, don't ask for help on it!||||

    Comment


    • #3
      Got it to work using getComputedStyle and getPropertyValue. Thanks. For further reference, the solution:

      Code:
      CSS:
      img {opacity: 0.3;}
      
      JavaScript\:
      function lighten(object) {
        var objectStyle = window.getComputedStyle(object,"");
        var opacity = objectStyle.getPropertyValue("opacity");
        counter = window.setInterval(fade,30);
        function fade() {
          opacity = (opacity * 100 + 5) / 100;
          object.style.opacity = opacity;
          if (opacity == 1) {
            clearInterval(counter);
            }
          }
        }
      function darken(object) {
        window.clearInterval(counter);
        object.style.opacity = "";
        }
      
      HTML:
      <img alt="[test object]" width="320" height="324" src="object.png" 
      onmouseover="lighten(this);" onmouseout="darken(this);">

      Comment


      • #4
        the full syntax is

        var objectStyle = document.defaultView.getComputedStyle(object,null)

        but it works only in Mozilla. IE uses other method, currentStyle, thus for a crossbrowser code, you should do something like:
        Code:
        var CSSval;
        if(object.currentStyle){
        CSSval = object.currentStyle[styleProp]
        }
        else if(window.getComputedStyle){
        CSSval = document.defaultView.getComputedStyle(object,null).getPropertyValue(styleProp);
        }
        Nor opacity CSS property is supported by IE. IE uses

        filter: alpha(opacity=value);

        where value takes values from 0 to 100
        KOR
        Offshore programming
        -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

        Comment


        • #5
          Originally posted by Kor View Post
          the full syntax is

          var objectStyle = document.defaultView.getComputedStyle(object,null)
          I'll keep this in mind.

          Originally posted by Kor View Post
          but it works only in Mozilla. IE uses other method, currentStyle […]
          I already derived this from _Aerospace_Eng_'s resource. getComputedStyle worked in more than Mozilla though as Opera was rendering it correctly in addition to Firefox. It turns out that I didn't need it though since it makes more sense to reference the opacity property in the script rather than the stylesheet since I wouldn't want semi-opaque images if JavaScript were to be disabled. Still, I learned a new technique, which is important.

          Originally posted by Kor View Post
          Nor opacity CSS property is supported by IE. IE uses

          filter: alpha(opacity=value);

          where value takes values from 0 to 100
          Mhm... HTML and CSS are my specialty so I'm aware of Internet Explorer's short-comings in that regard. I'm planning on making the script work for that browser too; I was just having a bit of trouble with the alpha filter causing the other browsers to throw errors. Pretty sure I can fix that, but now it seems that I also need to learn something like attachEvent to replace setAttribute.

          I decided to add a reverse fade to the script, so, for interest, the current non-IE–accommodating code is below. The original demo document has been updated as well.

          Code:
                var initialOpacity = 0.3;
                var opacity = initialOpacity;
                var maxOpacity = 1;
                var fadeInCounter;
                var fadeOutCounter;
                var interval = 30;
                var fadeIncrement = 0.05;
                var fixedDigits = 2;
                window.onload = function setOpacity() {
                  var imageArray = document.getElementsByTagName("img");
                  var i = 0;
                  while (imageArray.length > i) {
                    imageArray[i].setAttribute("onmouseover","lighten(this);");
                    imageArray[i].setAttribute("onmouseout","darken(this);");
                    imageArray[i].style.opacity = initialOpacity;
                    ++i;
                    }
                  }
                function lighten(object) {
                  window.clearInterval(fadeOutCounter);
                  fadeInCounter = window.setInterval(fadeIn,interval);
                  function fadeIn() {
                    opacity = (parseFloat(opacity) + fadeIncrement).toFixed(fixedDigits);
                    object.style.opacity = opacity;
                    if (opacity >= maxOpacity) {
                      clearInterval(fadeInCounter);
                      }
                    }
                  }
                function darken(object) {
                  window.clearInterval(fadeInCounter);
                  fadeOutCounter = window.setInterval(fadeOut,interval);
                  function fadeOut() {
                    opacity = (parseFloat(opacity) - fadeIncrement).toFixed(fixedDigits);
                    object.style.opacity = opacity; 
                    if (opacity <= initialOpacity) {
                      clearInterval(fadeOutCounter);
                      }
                    }
                  }

          Comment


          • #6
            Just use the DOM 1 method of
            Code:
            element.eventhandler = function()
            {
            // do something
            }
            onclick, onblur, onfocus, onmouseover, and onmouseout I do believe need to be set this way for IE.
            Code:
            element.onmouseover = function()
            {
            lighten(this);
            }
            ||||If you are getting paid to do a job, don't ask for help on it!||||

            Comment


            • #7
              opacity = (parseFloat(opacity) - fadeIncrement).toFixed(fixedDigits);
              Does this work? toFixed() returns a string, not a decimal number.
              KOR
              Offshore programming
              -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

              Comment


              • #8
                Originally posted by Kor View Post
                Does this work? toFixed() returns a string, not a decimal number.
                It's working fine for me and you can see a demonstration of the code on the demo page I posted links to. I didn't know that toFixed() returns a string, but object.style.opacity seems to have no problem accepting either a numerical string or a floated number. Then again maybe it converts it to one or the other and I haven't noticed.

                By the way, I'll post the finished Internet Explorer-compatible code when I'm through writing it. I'm still having a bit of trouble figuring out that code _Aerospace_Eng_ posted and object detection doesn't seem to be working because Internet Explorer processes instructions contained by if (imageArray[i].setAttribute) for some reason.

                Comment


                • #9
                  What are you having trouble with?
                  Code:
                  imageArray[i].onmouseover = function()
                  {
                  lighten(this);
                  }
                  imageArray[i].onmouseout = function()
                  {
                  darken(this);
                  }
                  There isn't much to it really.
                  ||||If you are getting paid to do a job, don't ask for help on it!||||

                  Comment


                  • #10
                    Originally posted by _Aerospace_Eng_ View Post
                    What are you having trouble with?
                    I was having trouble since that code seems to use a method named function, which I found confusing. I tried changing “function” to something else (i.e., function2 and function3) and it wasn't working. I also tried looking it up and couldn't find anything on whatever that technique or combination of code is called.

                    Anyway, I got it working now. I had to scrap the object detect for setAttribute since Internet Explorer claims to support that yet doesn't. Apparently, that code works in Firefox and Opera also so I was able to get by with removing setAttribute altogether. The end result isn't as pretty as the previous code, but it works in the latest versions of all three of the mentioned browsers; in Internet Explorer's case, I used version 7 Release Candidate 1. I also found that Microsoft didn't fix the alt attribute producing tooltips issue as I had thought. >_<

                    Anyway, I said I'd post the finished result. Internet Explorer 7 RC1-compatible demo: http://jsg.byethost4.com/fade+IE.html. And the source code:
                    Code:
                    <?xml version="1.0" encoding="utf-8"?>
                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                    
                    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
                      <head>
                    
                        <title>XHTML 1.0 Strict Document</title>
                    
                        <style type="text/css">
                          * {
                            margin: 0;
                            }
                          html, body, #container {
                            height: 100%;
                            }
                          html {
                            background-color: #222; 
                            color: white;
                            }
                          body {
                            display: table; 
                            width: 100%;
                            }
                          #container {
                            display: table-cell; 
                            vertical-align: middle;
                            }
                          img {
                            display: block;
                            margin: 0 auto;
                            }
                        </style>
                    
                        <!--[if IE]>
                        <style type="text/css">
                          #container {
                            position: relative;
                            overflow: visible;
                            }
                          #outer {
                            position: absolute;
                            top: 50%;
                            }
                          #inner {
                            position: relative;
                            top: -50%;
                            }
                        </style>
                        <![endif]-->
                    
                        <script type="text/javascript" defer="defer">
                          var initialOpacity = 0.3;
                          var opacity = initialOpacity;
                          var maxOpacity = 1;
                          var fadeInCounter;
                          var fadeOutCounter;
                          var interval = 30;
                          var fadeIncrement = 0.05;
                          var fixedDigits = 2;
                          window.onload = function setOpacity() {
                            var imageArray = document.getElementsByTagName("img");
                            var i = 0;
                            while (imageArray.length > i) {
                              imageArray[i].onmouseover = function() {
                                lighten(this);
                                }
                              imageArray[i].onmouseout = function() {
                                darken(this);
                                }
                              if (imageArray[i].filters) {
                                imageArray[i].style.filter = "alpha(opacity=" + (initialOpacity * 100) + ")";
                                }
                              else {
                                imageArray[i].style.opacity = initialOpacity;
                                }
                              ++i;
                              }
                            }
                          function lighten(object) {
                            window.clearInterval(fadeOutCounter);
                            fadeInCounter = window.setInterval(fadeIn,interval);
                            function fadeIn() {
                              opacity = (parseFloat(opacity) + fadeIncrement).toFixed(fixedDigits);
                              object.style.opacity = opacity;
                              if (object.filters) {
                                object.style.filter = "alpha(opacity=" + (opacity * 100) + ")";
                                }
                              if (opacity >= maxOpacity) {
                                clearInterval(fadeInCounter);
                                }
                              }
                            }
                          function darken(object) {
                            window.clearInterval(fadeInCounter);
                            fadeOutCounter = window.setInterval(fadeOut,interval);
                            function fadeOut() {
                              opacity = (parseFloat(opacity) - fadeIncrement).toFixed(fixedDigits);
                              object.style.opacity = opacity;
                              if (object.filters) {
                                object.style.filter = "alpha(opacity=" + (opacity * 100) + ")";
                                }
                              if (opacity <= initialOpacity) {
                                clearInterval(fadeOutCounter);
                                }
                              }
                            }
                        </script>
                    
                      </head>
                      <body>
                        <div id="container">
                          <div id="outer">
                            <div id="inner">
                    
                              <img alt="This is a 320×324 pixel portrait of Tōshirō Hitsugaya." 
                    width="320" height="324" src="object.png"/>
                    
                            </div>
                          </div>
                        </div>
                      </body>
                    </html>

                    Comment


                    • #11
                      setAttribute does work in IE but it doesn't seem to work for event handlers but you can set ids, hrefs, srcs, and values among some other stuff. The function() thing is an anonymous function that was assigned to the event handler. It stays the same all of the time. The stuff within it is what matters. Hmm this line
                      Code:
                      <?xml version="1.0" encoding="utf-8"?>
                      is putting IE6 into quirksmode.
                      ||||If you are getting paid to do a job, don't ask for help on it!||||

                      Comment

                      Working...
                      X