1

I'm making a page with lots of iframes on it, the websites in the iframes have ads in them and to make the page more viewable to people with adblock, I need to display different stylesheets.
Basically what I want to do is.. if adblock (display this stylesheet) else (display this stylesheet).

I have the code working to detect if adblock is present, but when I try to do the if else statement..the whole page is blank. Here's the code:

<script>
(function(){
    if($("#fakead").css('display')=="none")
    {
        document.write("<link href='css/adblock.css' rel='stylesheet' type='text/css'>")
    }
    else
    { 
        document.write("<link href='css/noadblock.css' rel='stylesheet' type='text/css'>")
    }
});
</script>

I'm extremely new to Javascript so my apologies if the code is terrible.

Thanks for any help

1
  • A simple reminder: when using document.write(), you are basically writing to the webpage. So there's a lesson for the day :) Commented Nov 1, 2013 at 13:55

2 Answers 2

4

You should not use document.write method. As I see you use jQuery, so in jQuery you can do like this:

$( function() {
    if($("#fakead").css('display')=="none") {
        $("<link href='css/adblock.css' rel='stylesheet' type='text/css'/>").appendTo( 'head' );
    } else { 
        $("<link href='css/noadblock.css' rel='stylesheet' type='text/css'/>").appendTo( 'head' )
    }
});

Please note: link element should be placed in <head> section. Read more in w3c.

Sign up to request clarification or add additional context in comments.

7 Comments

You are a wonderful person. Thank you very much! I'll select your answer as the correct one as soon as the 10 minutes have passed.
This answer is fine as it was first and shows you how to do it with jQuery, but for the sake of maintenance i'd take @Mikes code and refactor it into a generic function like function addStyle(path) { ... }
I've actually started to have a problem with the code. At first it worked perfectly then all of a sudden it started to default to "noadblock.css" regardless of whether adblock was installed or not.
I honestly don't know, I slapped the code in there as is and it was fine until it wasn't.
@Kerblooy are there any JS errors in the console? Maybe you have a link to check?
|
4

Pure JS option:

var el = document.createElement("link");
el.type = "text/css";
el.rel = "stylesheet";
el.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(el);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.