Page 1 of 2 12 LastLast
Results 1 to 10 of 19

Thread: Toggle Background Img

  1. #1
    Join Date
    Nov 2005
    Posts
    26
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default Toggle Background Img

    Anyone know how to toggle a CSS Background Image with Javascript? This is as far as i've gotten but it doesn't really work...

    Code:
    var captions = document.getElementsByTagName('caption')
    var captionLength = captions.length
    	
    function changeBackground(){ 
    	for(var i = 0;i < captionLenght; i++) {
       		var nodeObj = captions.item(i)
       		if( nodeObj.style.background-image = '/minus-bg.gif') {
           		nodeObj.style.background-image = '/plus-bg.gif';
        	}
       		else {
            	nodeObj.style.background-image = '/minus-bg.gif';
        	}
    	}
    }
    
    function setBG(){ 
    	for(var i = 0;i < captionLenght; i++) {
       		var nodeObj = captions.item(i)
       		nodeObj.onClick=changeBackground();
    	}
    }
    /*--------------------------------------------------*/
    window.onload = function() {
    	setBG();
    }

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    This code looks very bloated to me. I'm not familiar with the .item(i) method of referencing elements in an array. It may be fine, just not what I am used to. I would use captions[i] in place of captions.item(i). Also, when assigning an onclick in this manner, it must be defined as function and onclick is far preferable to onClick (less chance the script parser will reject it), for example, where you have:

    Code:
    nodeObj.onClick=changeBackground();
    it needs to be:

    Code:
    nodeObj.onclick=function(){changeBackground(this);}
    The red part, a reference to the individual element is not crucial but, I'll use it in just a moment.

    Now, we need to think a bit about the changeBackground() function itself. Aside from your using only one equal sign in the if statement (two are required when testing equality) the code assigns this as the onclick event for each individual caption element. Do we really want the code in changeBackground() executed each time an individual caption element is clicked? Don't we want something more like this:

    Code:
    function changeBackground(el){ 
       		if (el.style.backgroundImage == '/minus-bg.gif') 
           		el.style.backgroundImage = '/plus-bg.gif';
       		else
       		el.style.backgroundImage = '/minus-bg.gif';
    }
    Notes: Camel notation is required in place of hyphenated style properties in javascript. Not knowing your directory structure I have left '/minus-bg.gif' and like literals as is. Using the leading / means the file is in the root directory of either the domain (if live) or of the hard drive (if local). More likely you are looking for a file in the same directory as the page the script is on. If so, get rid of the leading /. If you are working across an entire site with a rich directory structure, use the exact path from the root to the image file ex:

    Code:
    'c:/webfiles/mysite/images/minus-bg.gif'
    when working locally and:

    Code:
    'http://www.mysite.com/images/minus-bg.gif'
    when uploading to the server. These are only example paths, change them in the code to reflect actual conditions. To summarize (with further simplifications included), this is how I would go about it:

    Code:
    <script type="text/javascript">
    function changeBackground(el){ 
       		if (el.style.backgroundImage == 'minus-bg.gif') 
           		el.style.backgroundImage = 'plus-bg.gif';
       		else
           		el.style.backgroundImage = 'minus-bg.gif';
    }
    
    function setBG(){ 
    	var captions = document.getElementsByTagName('caption')
    	for(var i = 0;i < captions.length; i++)
       	captions[i].onclick=function(){changeBackground(this);}
    }
    
    window.onload = setBG;
    </script>
    Last edited by jscheuer1; 11-09-2005 at 05:55 AM.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1
    I'm not familiar with the .item(i) method of referencing elements in an array.
    Not, an array: a collection.

    Objects that implement the HTMLCollection interface have item and namedItem methods. These are primarily for languages like Java. ECMAScript is expressive enough so that bracket notation can replace both of these (though they should still be implemented).

    Also, when assigning an onclick in this manner, it must be defined as function and onclick is far preferable to onClick (less chance the script parser will reject it),
    Your assessment thus far is correct, but I disagree with the conclusion:

    for example, where you have:

    Code:
    nodeObj.onClick=changeBackground();
    it needs to be:

    Code:
    nodeObj.onclick=function(){changeBackground(this);}
    Simply remove the function call:

    Code:
    nodeObj.onclick = changeBackground;
    The changeBackground function can now be redefined to use the this operator to refer to its node:

    Code:
    function changeBackground() {
      var style = this.style;
    
      if(style && ('string' == typeof style.backgroundImage)) {
        style.backgroundImage = (-1 != style.backgroundImage.indexOf('minus-bg'))
                              ? 'url(/plus-bg.gif)'
                              : 'url(/minus-bg.gif)';
      }
    }
    Notice the addition of the url(...) functional notation. This must be included when specifying URLs in CSS.

    Mike

  4. #4
    Join Date
    Nov 2005
    Posts
    26
    Thanks
    2
    Thanked 1 Time in 1 Post

    Default

    ok, i'm confused... doesn't "backgroundImage" have to be "background-image"? perhaps someone could post a working example of this that we can mull over?

  5. #5
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by wyclef
    ok, i'm confused... doesn't "backgroundImage" have to be "background-image"?
    In CSS, yes. However in a script, that would be interpreted as "subtract image from background", which is clearly undesirable.

    Code:
    if(document.getElementsByTagName) {
      this.onload = function() {
        var captions = document.getElementsByTagName('caption');
    
        for(var i = 0, n = captions.length; i < n; ++i) {
          captions[i&#93;.onclick = changeBackground;
        }
      };
    }
    using the changeBackground function I posted above.

    Mike

  6. #6
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    I was going to respond to your comments, but it seems that you've deleted the post, so I'll just post my inevitable example.

    Mike

  7. #7
    Join Date
    Nov 2005
    Posts
    93
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Notice the addition of the url(...) functional notation. This must be included when specifying URLs in CSS.

    Mike
    I'm confused too: Is this CSS or Javascript? or a mixture of both?

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by Wedgy
    I'm confused too: Is this CSS or Javascript? or a mixture of both?
    DHTML, don't you just love it! The answer, if I understand the question correctly is 'combination of both'. DHTML isn't really anything at all, technically speaking. It can draw from whatever is available.

    While I am at it, I never responded to Mike's comments on my script in this thread. With the exception of my just plain error about forgetting to use the proper:

    Code:
    el.style.backgroundImage = "url('/minus-bg.gif')";
    I think my code would work fine. However, I understand and like all of Mike's suggestions on this one (the background changing script), very neat and efficient. Good one Mike!
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Wedgy
    Quote Originally Posted by Mike
    Notice the addition of the url(...) functional notation. This must be included when specifying URLs in CSS.
    I'm confused too: Is this CSS or Javascript? or a mixture of both?
    Assuming you're just referring to my mention of the url(...) functional notation (as that's what you quoted), that's defined by CSS.

    See 4.3.4 URL + URN = URI.

    Mike

  10. #10
    Join Date
    Nov 2005
    Posts
    93
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Wow, thanks for the link.
    I am still confused however:
    In the link you provided, there is no indication or example of "url(blah)" being used in the middle of a Javascript function. It is described as a CSS2 definition, with its home in CSS stylesheets. Your code:
    Code:
    function changeBackground() {
      var style = this.style;
    
      if(style && ('string' == typeof style.backgroundImage)) {
        style.backgroundImage = (-1 != style.backgroundImage.indexOf('minus-bg'))
                              ? 'url(/plus-bg.gif)'
                              : 'url(/minus-bg.gif)';
      }
    }
    This looks an awful lot like a piece of Javascript, and since I am assuming Javascript was invented before CSS2, I am surprised to see "url(blah)" here. I'd be even more surprised to find it described in a tutorial on Javascript due to the apparent anachronism.

    What have I still got wrong here?

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •