Jump to content

Topic on Project:Support desk

How to use JavaScript document.write in jQuery ready function?

7
Stefahn (talkcontribs)

We want to add content before every 3rd headline within the content area. We do so with jQuery in Common.js. Now we want to add a JavaScript code for splittesting. This code uses document.write.

From I learned that one can not use document.write in Common.js. And says that I can't use jQuery (ready function) within the articles itself.

So how can I use the jQuery ready function in combination with document.write in MediaWiki?

Ciencia Al Poder (talkcontribs)

You can not use document.write in current HTML code on any modern browser (unless you want to render a completely blank and unusable page).

You'll need to replace document.write with DOM manipulation.

Stefahn (talkcontribs)

For some reason document.write within this JavaScript code works fine, if added statically to a page - see the second line here: https://secret-wiki.de/wiki/Hilfe:Sandkasten2 (the JavaScript outputs just one single line of German text)

My question is still: How can I use the jQuery ready function in combination with document.write in MediaWiki?

Ciencia Al Poder (talkcontribs)

You can't use document.write in MediaWiki. Period.

What does document.write do? Write text on the page. Where on the page? Where the document.write is present.

What do you expect document.write to write to if placed inside a JavaScript file, or even inside a jQuery ready function???

Stefahn (talkcontribs)

As I mentioned the second line on https://secret-wiki.de/wiki/Hilfe:Sandkasten2 is generated by document.write. So MediaWiki seems to be able to handle it if I put the JavaScript directly on a page.

I need the jQuery ready function so that I can do the following:
$( "h2:nth-of-type(3n+3)" ).before('HTML code containing the JavaScript code with document.write');

Ciencia Al Poder (talkcontribs)

I'm not going to repeat myself, since my the last message already covers that.

You're trying to use DOM functions with jQuery to inject HTML where you want (which is the right thing to do), but instead of normal HTML you want to inject a piece of JavaScript that does document.write to write HTML. Think how absurd is this.

Stefahn (talkcontribs)

Okay, I think I got it now.

I can use document.write if I add the JavaScript code directly on my article (with Extension:Secure_HTML for example). But I can't use it within other JavaScript code.

Maybe there's a way to save the html that document.write produces in a variable, which is then used by the jQuery ready function...

Reply to "How to use JavaScript document.write in jQuery ready function?"