Solved

Using Event Handling to Notify When A Div Changes Size?

Posted on 2008-06-17
5
1,567 Views
Last Modified: 2013-11-19
I'd like to use event handling to notify an external JavaScript (JS) file of when a div grows in size.  How do I do that, with emphasis on making it work in IE6?  My problem in greater detail:

The solution I'm working on includes an external JS file and a 2px-wide div with a script block that calls an image from another server.  Once the call returns the image, the div expands to fit the image inside it, usually larger than 100px-wide.  The div also has a tab with a link to a function meant to close the div.  Since the tab should stay hidden on occasions when the image does not appear, the external JS has a recursive function called 'showHideButtonIfAdScheduled()' that checks the div size and uses CSS to un-hide the tab if the image is present and the div has expanded beyond 2px width...  This method worked just fine until the website it is deployed on underwent a new design.  Since the new design which takes more time to load than the old design did, the solution stopped working on IE6 versions of the page - you'll notice the script runs recursively 13 times in Firefox and IE7 and 1000 time in IE6.  Since running the recursive function 1000 times doesn't work and is unacceptable anyway, I'd like to use event handling instead.  If the div fires some detectable event when its' size changes (???), I'll run the showHideButtonIfAdScheduled() function without recursion on that event.

I have a cross-browser method for adding events but I'm not sure how to use it to get what I want.  
---------------------------------------------------------
function addEvent( element, evType, fn, useCapture )
{
      //If browser is Netscape/Mozilla...
      if ( element.addEventListener ) {
            element.addEventListener( evType, fn, useCapture );
            return true;
      }
      //If browser is Internet Explorer...
      else if ( element.attachEvent ) {
            var r = element.attachEvent( 'on' + evType, fn );
            return r;
      }
      //If browser is neither Netscape/Mozilla or IE...
      else {
            element[ 'on' + evType ] = fn;
      }
}

addEvent( element, 'event', eventListener, false );

function eventListener( e )
{
      var t = window.event ? window.event.srcElement : e ? e.target : null;  
}
---------------------------------------------------------

Can you help?  Please do not make suggestions without proving that it works first; that's why I included the code in this post.  The solution is set to show the image once per day so be sure to clear your cookies after each test; refreshing alone will not show the image.

Thanks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Test</title>

 

<script type="text/javascript"  language="javascript">

//THIS IS THE EXTERNAL SCRIPT, PLACED INTO THE PAGE FOR EASE OF DEPLOYMENT

 

var IA_sitecode;

var timeout;

var showAd = false;

var adVisible = false;

 

/* -- COOKIE LOGIC -- */

function cookiesEnabled() {

	Set_Cookie( 'test', 'none', '', '/', '', '' );

/*

If Get_Cookie succeeds, cookies are enabled, since 

the cookie was successfully created.

*/

	if ( Get_Cookie( 'test' ) ) {

		cookie_set = true;

		Delete_Cookie('test', '/', '');

	} else {

		document.write( 'cookies are not currently enabled.' );

		cookie_set = false;

	}

	return cookie_set;

}

 

function setQuestCookie() {

	var cookie_name = "questFlash" + IA_sitecode;

	Set_Cookie( cookie_name, "already seen", 24, "/", "", "" );

}

 

function Set_Cookie( name, value, expires, path, domain, secure ) {

// set time, it's in milliseconds

	var today = new Date();

	today.setTime( today.getTime() );

/*

if the expires variable is set, make the correct expires time, the current 

script below ( expires = expires * 1000 * 60 * 60 * 24 ) will set 'expires' 

for 'X' number of days; to make it set for hours, delete * 24, for minutes, 

delete * 60 * 24

*/

	if ( expires )	{

		expires = expires * 1000 * 60 * 60;

	}

	var expires_date = new Date( today.getTime() + (expires) );

	

	document.cookie = name + "=" +escape( value ) +

		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 

		( ( path ) ? ";path=" + path : "" ) + 

		( ( domain ) ? ";domain=" + domain : "" ) +

		( ( secure ) ? ";secure" : "" );

}

 

// this function gets the cookie, if it exists

function Get_Cookie( name ) {

	

	var start = document.cookie.indexOf( name + "=" );

	var len = start + name.length + 1;

	if ( ( !start ) &&	( name != document.cookie.substring( 0, name.length ) ) ) {

		return null;

	}

	if ( start == -1 ) {

		return null;

	}

	var end = document.cookie.indexOf( ";", len );

	if ( end == -1 ) {

		end = document.cookie.length;

	}

	return unescape( document.cookie.substring( len, end ) );

}

			

// this deletes the cookie when called

function Delete_Cookie( name, path, domain ) {

	if ( Get_Cookie( name ) ) {

		document.cookie = name + "=" +

			( ( path ) ? ";path=" + path : "") +

			( ( domain ) ? ";domain=" + domain : "" ) +

			";expires=Thu, 01-Jan-1970 00:00:01 GMT";

	}

}

 

function setIASiteCode( sitecode ) {

	IA_sitecode = sitecode;

}

 

 

/* -- VISUAL LOGIC -- */

function appear() {

	var the_style = getStyle( "floatingflash" );

	the_style.display = 'block';

 

	/*

	//Logic for sliding the target div onto the stage

	//'endPosition' determines where the ad will stop; higher value will equal lower point on page

	var endPosition = 300;

	

	if ( the_style ) {

		var current_top = parseInt( the_style.top );

		var new_top = current_top + 5;

		if ( document.layers ) {

			the_style.top = new_top;

		} else {

			the_style.top = new_top + "px";

		}

		if ( new_top < endPosition ) {

			the_timeout = setTimeout( 'appear();', 10 );

		}

 

		//Adjust inline style on page

		//the_style.marginLeft = 38 + "%";

	}

	*/

	

	

} // appear

 

function disappear() {

	var the_style = getStyle( "floatingflash" );

	the_style.display = 'none';

} // disappear

 

function getStyle(ref) {

	if( document.getElementById && document.getElementById( ref ) ) {

		return document.getElementById( ref ).style;

	} else if ( document.all && document.all( ref ) ) {

		return document.all( ref ).style;

	} else if ( document.layers && document.layers[ ref ] ) {

		return document.layers[ ref ];

	} else {

		return false;

	}

} // getStyle

 

function browserIsIE6() {

	var browser = navigator.appName;

	var ie7 = ( document.all && !window.opera && window.XMLHttpRequest ) ? true : false;

	// browser != "Microsoft Internet Explorer"

	if ( browser != "Microsoft Internet Explorer" && ie7 == false ) {

		return true;

	}

	else {

		return false;	

	}

}

 

function showHideButtonIfAdScheduled( runcount ) {

	/* Show the interstitial div's close button ('X') if an ad loads into 

	the interstial div tag (a.k.a. "floatingflash").  If an ad is not loaded,

	the div will not grow passed the 'emptyDivSize'. */

	var emptyDivSize = 2;

	var recursionLimit;

	if ( browserIsIE6() ) {

		recursionLimit = 1000;

	}

	else {

		recursionLimit = 13;

	}

	var hideButtonStyle = getStyle( "hideButton" );

	var curWidth = parseInt( document.getElementById( "floatingflash" ).offsetWidth );

	var curHeight = parseInt( document.getElementById( "floatingflash" ).offsetHeight );

	//alert( "RUNCOUNT: " + runcount );

	if ( curWidth >= emptyDivSize && curHeight >= emptyDivSize ) {

		//Show button by changing display style from 'none' to 'block'

		hideButtonStyle.display = 'block';

	}

 

	//If IE6's bad timing issue failed to set display to 'block', try again

	if ( runcount < recursionLimit ) {

		if ( hideButtonStyle.display != 'block' && showAd ) {

			showHideButtonIfAdScheduled( runcount++ );

		}

	}

}

 

function fixUppermostFlashLayerBug() {  

	var browser = navigator.appName;

	var ie7 = ( document.all && !window.opera && window.XMLHttpRequest ) ? true : false;

	// browser != "Microsoft Internet Explorer"

	if ( browser != "Microsoft Internet Explorer" ) {

	   //...then apply Firfox's Flash overlap fix

	   document.getElementById('floatingflash').innerHTML = document.getElementById('floatingflash').innerHTML.replace( /="window"/g, '="transparent"');

	   document.getElementById('adscol').innerHTML = document.getElementById('adscol').innerHTML.replace( /="window"/g, '="transparent"');

	} else {

		//...then apply IE's Flash overlap fix

	   document.getElementById('floatingflash').onchange = setTimeout( 'checkIfImageOrFlash()', 500 );

	}

}

 

function checkIfImageOrFlash() {  //UNFINISHED - NEED TO WORK ON IE SECTION

 

	//hideButtonTab is at 'childNodes[1]'.  The dynamic object ('Flash movie/SCRIPT' or 'A tag w/ child IMG tag')

	//should be located at 'childNodes[5]'

	var ff = document.getElementById( 'floatingflash' ).childNodes[ 5 ];

	var ac = document.getElementById( 'adscol' );

	//If dynamic object inside floatingflash is a link with a child image...

	if ( ff.tagName.toLowerCase() == "a" ) {

		if ( ff.firstChild.tagName.toLowerCase() == "img" ) {

			ac.innerHTML = ac.innerHTML.replace( /="window"/g, '="opaque"');

		}

	}

	//...if not, it is a flash movie

	else {

        ac.innerHTML = ac.innerHTML.replace( /="window"/g, '="transparent"');

	}

}

 

/* -- MASTER TIRGGER FUNCTION ( place this function in body tag's onLoad method ) -- */

function checkIfInterstitialAdShouldRun() {

	if ( showAd ) {

		appear();

		showHideButtonIfAdScheduled( 1 );

	}	

}

 

/* -- SECONDARY TIRGGER FUNCTION (appears inside HTML insterstitial div (i.e. floatingflash))-- */

function userHasNotSeenAd() {

   var enableAd = true;

   if ( Get_Cookie( "questFlash" + IA_sitecode )!= null ) {

      enableAd = false;

   } else {        

      setQuestCookie();

      enableAd = true;

   }

   if ( !cookiesEnabled() ) {

      enableAd = true;

   }

   return enableAd;

}

 

		

//alert( "The target childNode ID is: " + targetObj.id + "\n" +

//	   "The childNode tagName is: " + targetObj.tagName + "\n" +

//	   "The childNode type is: " + typeof targetObj + "\n" +

//	   "Content: \n" + targetObj.innerHTML );

//alert( "hideButtonStyle.display: " + hideButtonStyle.display + " \n" + "showAd: " + showAd  + "\n" + "runcount: " + runcount + " \n" + "curWidth: " + curWidth + " \n" + "curHeight: " + curHeight );

</script>

 

<script type="text/javascript" language="javascript">

 

// This script function loads all of the display javascript

window.onload = function(){

		checkIfInterstitialAdShouldRun();

}

 

</script>

<style>

#floatingflash {

	position:absolute;

	display: block;

	z-index: 100; /* z-index may be set also be set as inine style */

}

 

a#hideButton  {

	/* Display property is changed to from 'none' to 'block' upon 

	triggering the 'showHideButtonIfAdScheduled()' function */

	display: none;

	float: right;

	height: 16px;

	border-top: 1px solid #000000; /* black */

	border-right: 1px solid #000000; /* black */

	border-left: 1px solid #000000; /* black */

	padding-top: 1px;

	padding-right: 8px;

	padding-bottom: 1px;

	padding-left: 5px;

	color: #000000;

	background-color:#CCCCCC;

	font-size: 11px;

	font-family: Arial, Verdana, Helvetica, sans-serif;

	font-weight: 600;

	text-decoration: none;

	text-align: left;

	z-index: 99;

}

 

a#hideButton:hover {

	color: #2080AF;

	background-color:#CCCCCC;

}

 

#hideButtonTab {

	width: 100%;

	position: absolute;

	top: -18px;

}

 

</style>

</head>

 

<body>

 

<div id="floatingflash" style="display:none;top:300px;left:200px;">

  <!-- This is the close button that appears over

        generated/visible ads -->

  <div id="hideButtonTab"> <a id="hideButton" href="javascript:disappear();">Close [ X ]</a> </div>

  <!-- This is the link to the remote OAS ad tag -->

  <script type="text/javascript">

		setIASiteCode( "TESTING" );

        if ( userHasNotSeenAd() ) {

           showAd = true;

           document.write('<scr'+'ipt language="JavaScript" type="text/javascript" src="http://oascentral.law.com/RealMedia/ads/adstream_jx.ads/interstitial.law.com/testing/@x96"></scr'+'ipt>');

		}

        </script>

 

</div>

 

</body>

</html>

Open in new window

0
Comment
Question by:JaeWebb
  • 3
  • 2
5 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21811963
Erm

<div id="imgDiv"
style="display:none"><img id="img1" src="1pxblank.gif"
onLoad="if (this.src.indexOf('1px')!=0) this.parentNode.style.display=''"
onError="this.parentNode.style.display='none'"
/></div>
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 21811991
Ok, I looked at your source.

The script returned from the ad server sucks.
Why not use and iframe and onLoad unhide it?
0
 

Author Comment

by:JaeWebb
ID: 21813397
The company I work for uses this 'oascentral' company as an advertising service.  They keep track of viewings and clicks on the particular ads served to our site so one of my minimum requirements is to display ads served from this location:

src="http://oascentral.law.com/RealMedia/ads/adstream_jx.ads/interstitial.law.com/testing/@x96"

The part of the link where it says 'testing' triggers the display of a demo ad that is not tracked.  When this code is live in our system, the 'testing' part will have a different code to trigger the display of image ads and/or flash ads that are tracked as normal...  Since I cannot control whether the ad object returned from the script is an image or flash, I'm not sure how to apply your solution.  Also, I don't know how to use iframe yet.
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 21814678
Start by putting this in an html file on its own

<div id="floatingflash" style="display:none;top:300px;left:200px;">
  <!-- This is the close button that appears over
        generated/visible ads -->
  <div id="hideButtonTab"> <a id="hideButton" href="javascript:disappear();">Close [ X ]</a> </div>
  <!-- This is the link to the remote OAS ad tag -->
  <script type="text/javascript">
            setIASiteCode( "TESTING" );
        if ( userHasNotSeenAd() ) {
           showAd = true;
           document.write('<scr'+'ipt language="JavaScript" type="text/javascript" src="http://oascentral.law.com/RealMedia/ads/adstream_jx.ads/interstitial.law.com/testing/@x96"></scr'+'ipt>');
            }
        </script>
 
</div>



then in the page you can have

<iframe style="display:none; width:300px;height:300px" onLoad="this.style.display='';" src="thePageYouJustmadeWithTheAdvertCode.html"></iframe>

change the 300px to whatever height and width the advert normally is

I am not sure this will work since I am not sure if the onload will trigger and if it triggers if there is a security issue, but it is worth a try
0
 

Author Comment

by:JaeWebb
ID: 21930211
mplungian,

Your solution rocked.  It took me some time to work with it, which is why I'm just now getting back to you.  I'm developing in a production environment so I had to study up on iFrames.  My project also required that I get creative with the iFrame by giving it zero height and width, transparency, and then transferring the sub-html file's inner HTML into the original target div.  Using the iFrame's onLoad property was key to making the product work.

Thanks again!
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Preface This is the third article about the EE Collaborative Login Project. A Better Website Login System (http://www.experts-exchange.com/A_2902.html) introduces the Login System and shows how to implement a login page. The EE Collaborative Logi…
JavaScript has plenty of pieces of code people often just copy/paste from somewhere but never quite fully understand. Self-Executing functions are just one good example that I'll try to demystify here.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Shows how to create a shortcut to site-search Experts Exchange using Google in the Chrome browser. This eliminates the need to type out site:experts-exchange.com whenever you want to search the site. Launch the Search Engine Menu: In chrome, via you…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now