Advanced CSS Printing – Using JavaScript Double-Click To Remove Unwanted DIVs

By  on  

Like any good programmer, I'm constantly searching around the internet for ideas and articles that can help me improve my code. There are thousands of talented programmers out there so I stumble upon some great articles and code snippets that I like to print out and use at a later time. The most disappointing part of finding a great article is seeing the printed result -- many times the article is unreadable and thus gets relegated to scratch-paper duty.

Once I realized I couldn't count on others to make the page print well, I decided to take things into my own hands. Of course I couldn't code a custom stylesheet every time I wanted to print from a different website -- who has time for that? I'm a Firefox junkie so I went to the Firefox extensions website and downloaded a great tool called Nuke Everything Enhanced. NEE is a great tool -- I can right-click on any html element I want to get rid of, select "Remove this object", and the object immediately disappears. Once I've removed all of the elements that make the page print poorly, I end up with a much-improved printout.

The programmer in me yearns for a better solution. NEE works great for my purposes, but what about everyone else? Not everyone uses Firefox and not everyone has the patience to right-click and remove 20 objects before they print a page. At lunch one day I got an idea. What if a person could double-click on a DIV and make the DIV disappear? Double-clicking serves no special function in any web browser (as far as the rendered page is concerned) and if a user does double-click, it's usually on a link or button, not a DIV.

Great idea? Maybe, but only if I could get it to work. With my cunning cleverness (arrogance) and driven personality (stubbornness), I grabbed my trusty MooTools library and went to work.

The Code

//add on DOMREADY
	window.addEvent('domready',function() {

		//get all divs with the "removable" class
		var divs = $$('div.removable');

		//for each removable div...
		divs.each(function(div) {

			//after the double-click...
			div.addEvent('dblclick',function() {
					//create transition
					var dwfx = new Fx.Styles(div, { duration:500, transition: Fx.Transitions.linear });
					//get the DIV width & height
					var coords = div.getCoordinates();
					//set the width and height so that when we empty the div, it wont look funky if
					//height and width styles aren't explicity set.
					div.setStyles({height:coords['height'], width:coords['width']});
					//remove the HTML inside the DIV for smoothness purposes
					div.setHTML('');
					//get rid of it!
					dwfx.start({'height':0,'width':0,'opacity':0,'margin':0,'padding':0});
			});

		});

	});

Now that the JavaScript framework is down, lets add the CSS removable class. I'll use the crosshair cursor and lightblue background to let the user know that the DIV is marked for potential removal.

.removable	{ cursor:crosshair; background:lightblue; }

You'll note that I didn't apply the script to every DIV on the page -- just the DIVs with the removable class. As the creator of the website, it's also your job to make sure the main content is not removable.

If you're thinking that a properly created print CSS file would avoid all of this, you may be right. My thought with this is that you can give the user control over what they want to print -- what if they want to print something on the page that the programmer didn't think should be printer? My MooTools script gives the user the power.

Do you see any potential problems with a script like this? Have any code or suggestions? If so, please share your ideas.

Recent Features

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

  • By
    jQuery Comment Preview

    I released a MooTools comment preview script yesterday and got numerous requests for a jQuery version. Ask and you shall receive! I'll use the exact same CSS and HTML as yesterday. The XHTML The CSS The jQuery JavaScript On the keypress and blur events, we validate and...

  • By
    pointer Media Query

    As more devices emerge and differences in device interaction are implemented, the more important good CSS code will become.  In order to write good CSS, we need some indicator about device capabilities.  We've used CSS media queries thus far, with checks for max-width and pixel ratios.

Discussion

  1. Brilliant idea, but I do think that even multiple print CSS files (configurable by the user) might work better. The whole problem is that users have a really hard time figuring out how to remove an element on purpose, and then those that just randomly double-click have no idea why the page header disappears pseudo-randomly.

    Good work with MooTools though, it’s my fav JS library too.

  2. Thank you for your input Eric! The above solution would only work when I could count on a semi-knowledgeable audience — most users want everything done for them and wouldn’t even catch on to the double-click. Thank you for your comments!

  3. sagiv

    i am developing automation and i am using this function to simulate ‘click’:(java scriot)

    this.clickObj = function clickObj(obj) {
            if ( obj == null ) {
                throw new Error(1108, "Can't click null object");
            }
    
            obj.click();
            this.checkSubmit();
            return this;
        };
    

    i need a function for double click …
    will be very happy to get some help.
    THX

  4. vaithiyanathan

    hai this is code very useful

  5. Kierra

    Hi
    That’s fab! I have a problem from the other side of the coin though. When my web page is printed, the css files are suddenly completely ignored and all the hidden divs show on the print.

    Do you by any chance know how to control the divs even when printing?
    Thanks in advance for any help!

  6. Kierra

    *cough cough* just realised how dumb that sounded. I obviously wasn’t concentrating when I read it the first time. Nevertheless, do you think you could use an onload function instead to make the div hiding automatic instead of it being manual?

    –If you’re thinking that a properly created print CSS file would avoid all of this, you may be right.– As regards this, I tend to find that the css files are ignored when it comes to printing, so this code may be a solution to that problem. Dunno tho, that could just be me being a novice :)

  7. I need something like this for a page I have which renders fine in most browsers, but in some there is a DIV (where I have stuffed Google Adsense) that sometimes blocks some of the content in an iFrame.

    You can see it on my page here: http://www.web-cam-search.com

    I could put the adsense in a DIV with a little red X in the top right corner and that would solve the problem… hopefully it’s not a violation of the Google TOS…

    Worth a try. It would only be to clean up the user experience.

  8. Great! But sometimes I double click on some words to select those words, or triple-click to select a line :D

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!