Is there a vanilla Javascript alternative for .html()? - javascript

I'm wanting to create an opposite affect to <noscript>. I don't want the content to load at all if Javascript isn't enabled, which is why I'm not interested in a display:none alternative, which still loads but just hides.
I came across this previous answer which has the desired affect (see updated answer).
HTML:
<div id="container"></div>
<script type="text/html" id="content">
<div class="test">HTML goes here</div>
</script>
jQuery:
$(document).ready(function() {
$('#container').html($('#content').html());
});
Is there anyway I can do this with Vanilla Javascript? I want the contents of the script to render as functional HTML.

often what is done is to set up your html as:
<html class="no-js">
<head>
<script>(function(H){H.className=H.className.replace(/\bno-js\b/,'js');})</script>
<!-- ... -->
</head>
<!-- ... -->
<div class="js-only">I only show up when js is enabled</div>
<!-- ... -->
</html>
and then have some css which hides that element
.no-js .js-only {
display: none;
}
the javascript replaces no-js with js in the <html> element which causes the div to display only when js is enabled

Related

A self contained Javascript/Html module - Is this possible?

[EDIT: I have possibly found another solution. Kooilnc's solution looks good. Is the solution at the bottom of this question better or worse than Kooilnc's?]
I have a div with associated javascript code. I would like to have the html for just this div and the associated javascript code all in one file, a kind of self contained 'module', eg
mydiv.html
<html>
<div id="Wibble" style="display: none;">
... loads of structure for just this div
</div>
<script type="text/javascript">
... loads of js functions just associated with this div
</script>
</html>
Then in my main page index.html I would like to include this 'module' in some way.
The only thing I have found is a Server Side Include:
index.html
<!DOCTYPE html>
<html>
<head>
... loads of stuff
</head>
<body>
... loads of other html structure
<!--#include FILE="mydiv.html" -->
... loads of other html structure and script tags
</body>
</html>
Question 1: Is there a better way of doing this?
Question 2: Should I have the html tag in mydiv.html as that will obviously put an html tag in index.html which is out of place?
Question 3: If that html tag in Q2 should not be there, how do I write the mydiv.html file so it has all the formatting and nice coloured structure in Visual Studio Code?
Edit:
Kooilnc's solution (below in the answers) looks good. Here is another solution I have found. It is working in my development environment Visual Studio Code. I need the javascript in my included html file in body's onload. Does anyone know if this solution will work on a server with my body onload requirement? Is it better or worse than Kooilnc's solution?
Jquery must be included with the normal <script> tag prior to this.
I insert this code within index.html
<!DOCTYPE html>
<html>
<head>
... loads of stuff
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</head>
<body>
... loads of other html structure
<div id="include_mydiv"></div>
<script>
$(function(){
$("#include_mydiv").load("mydiv.html");
});
</script>
... loads of other html structure and script tags
</body>
</html>
And mydiv.html did not have any <html> tags:
<div id="Wibble" style="display: none;">
... loads of structure for just this div
</div>
<script type="text/javascript">
... loads of js functions just associated with this div
</script>
You can try importing from template elements. Here is a simplified templating example that may be useful.
If you need to import from an external file, check this example I cooked up for you.
document.querySelectorAll(`[data-import]`).forEach( el => {
if (!el.dataset.imported) {
el.appendChild(document.querySelector(`#${el.dataset.import}`)
.content.cloneNode(true));
el.dataset.imported = `ok`;
}
});
<template id="someForm">
<script>
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.nodeName === `BUTTON`) {
alert(`Yes. I am handled`);
}
}
</script>
<button id="sub">Handle me!</button>
</template>
<template id="somethingElse">
<style type="text/css">
.red {color: red;}
</style>
<p class="red">I am appended too</p>
</template>
<div data-import="someForm"></div>
<div data-import="somethingElse"></div>
Use an Iframe
<iframe id="inlineFrameExample"
width="300"
height="200"
src="mydiv.html">
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

Hiding/showing content whether javascript is enable/disabled

I have seen some posts regarding wanting to do something like this, but I am at a loss to understand why my code doesn't work. I'm trying to make sure that users who visit a page have javascript enabled. If disabled, I want to hide all content and display a simple page with a message that the main page cannot be displayed without javascript.
I have the following:
<html>
<head><title>my site</title>
<noscript><style type="text/css">site {display:none;} </style></noscript>
</head>
<body onload="hideDiv()">
<div id="noscriptmsg">You need to have javascript enabled in order to view this site.</div>
<script type="text/javascript">document.getElementById("noscriptmsg").style.display = 'none';</script>
</body>
<body>
<div class="site">
<!--content -->
</div>
</body>
</html>
Currently this shows the correct javascript-enabled page, but a completely blank javascript-disabled page. What would cause this?
Why not use the build in noscript in one body tag:
<html>
<head><title>my site</title>
</head>
<body>
<noscript>
<style type="text/css">
#site {display:none;}
</style>
<div id="noscriptmsg">
You need to have javascript enabled in order to view this site.
</div>
</noscript>
<div id="site">
</div>
</body>
</html>
It looks like in the body onload you are trying to call the method hideDiv()
First, I'd recommend moving your script tag
<html>
<head><title>my site</title>
<noscript><style type="text/css">.site {display:none;} </style></noscript>
<script type="text/javascript">
// to the head tag
// and define the hideDiv() method
function hideDiv() {
document.getElementById("noscriptmsg").style.display = 'none';
}
</script>
</head>
<body onload="hideDiv()">
<div id="noscriptmsg">You need to have javascript enabled in order to view this site.</div>
<div class="site">
<!--content -->
</div>
</body>
</html>
and remove the extraneous body tags. You can use css to have the first div (the one with the notice) display at 100% width and 100% height. Also, someone pointed out you were missing the css class selector.

Define specific CSS-style only if JavaScript is enabled

My webpage contains a DIV. If Javascript is enabled, I want the DIV to be invisible (display: none;) when the page loads. If JS is disabled, I want it to be visible (display: block;).
I can do:
document.write('<div style="display:none;">...</div>');
or
document.getElementById('foo').style.display = 'none';
With the first code there won't be a DIV if JS is disabled. With the second, the DIV will be visible when the page loads and disappear when the JS is executed.
I'm too stupid to solve this.
Can I put JavaScript inside the <div>-tag to write only the style? Certainly not like this:
<div <script>document.write('style="display:none;"');</script>>
Maybe something like:
<div onLoad="document.write('<div style="display:none;">...</div>');">
Does someone have an idea?
One problem with displaying an element unless JS hides it is that, even with JS on, the element is likely to display until the JS kicks in. So it's often better to have some JS at the top of the file that adds a class to the root element straight away, to get in before the CSS loads. Here's a simple example (in my noob JS):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
(function() {
var root = document.querySelector('html');
root.className = "js";
}());
</script>
<style media="all">
div {width: 500px; height: 200px; background: blue;}
.js div {display: none;}
</style>
</head>
<body>
<div></div>
</body>
</html>
This is much better than using oldfashioned <noscript> and document.write() etc.
EDIT: I should just note that an easier way to target the html element is with document.documentElement. Thus, the code above could be written as—
<script>
(function() {
document.documentElement.className = "js";
}());
</script>
Why don't you just put the <div> in a <noscript>?
<noscript><div style="display:none;">...</div></noscript>
Now you don't even have to use Javascript to deal with it.

Can I not use embedded <style> CSS on Android?

I'm debugging a site on an Android HTC Sense. The site uses a lot of inserted content, which comes along with it's own CSS and JS like:
// wrapper id = snippet_id
<html>
<head>
<style type="text/css">
#snippet_id div {border: 1px solid red !important;}
div {border: 1px solid blue !important;}
</style>
</head>
<body>
<div>Hello World</div>
</body>
<html>
This is inserted into an existing page, so it sort these snippets are sort of like iFrames I guess.
Question:
Problem is, that while Javascript works fine, all CSS I'm specifying using <style> tags is being ignored. Any idea why?
EDIT:
Works on:
- Android 4.0.1
Does not work on:
- Android 2.3.1
- IOS 4.1
If I add the CSS to the main.css file being requested when the page loads, all is ok. If it's inside my gadget, it's not working.
EDIT:
So from what I can see, <style> does not seem to work on classes and id. If I use regular HTML elements as selectors it works.
EDIT:
My dev-site is here. I'm using a plugin called renderJs, which encapsultes HTML snippets (along with their CSS and JS) into resuable gadgets. Gadgets content will be appended to the page body, so although a gadget can act as a standalone HTML page, it can also be part of a page.
Example code from my page (I stripped out all gadgets but one below):
index.html - include index_wrapper gadget
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Organization" lang="en" class="render">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/overrides.css">
<script data-main="../js/main.js" type="text/javascript" src="../js/libs/require/require.js"></script>
<title></title>
</head>
<body class="splash">
<div data-role="page" id="index">
<div id="index_wrapper" data-gadget="../gadgets/index_wrapper.html"></div>
</div>
</body>
</html>
The page has a gadget called index_wrapper link - code below:
<!DOCTYPE html>
<head></head>
<body>
<div id="index_social" data-gadget="../gadgets/social.html"></div>
<p class="mini t" data-i18n="gen.disclaimer"></p>
</body>
</html>
Which has another gadget called social here. This gadget includes some CSS, but on the devices in question, it is ignored (just saw, I'm missing a </div> in the index_wrapper, so trying to see if that fixed the problem, too).
The code below includes my fix:
<!DOCTYPE html>
<head>
<style type="text/css" scoped>
// will be ignroed
.el {width: 1px;}
.menu_social {text-align: center; margin: 1em 0;}
.action_menu {display: inline-block;}
.follow_us {display: inline-block; margin: 0; padding: 0 .5em 0 0;}
...
</head>
<body>
<div class="menu_social">
<div>
<span class="el ui-hidden-accessible"></span><!-- fallback for CSS not working -->
<div data-role="controlgroup" data-type="horizontal" data-theme="c" class="action_menu">
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
(function () {
$(document).ready(function() {
var gadget = RenderJs.getSelfGadget();
// fallback for old devices which cannot load <style> css
if (gadget.dom.find(".el").css('width') !== "1px") {
require(['text!../css/social.css'], function (t) {
var x = '<style>'+t+'</style>';
gadget.dom.append(x);
});
}
// trigger enhancement
$(this).trigger("render_enhance", {gadget: gadget.dom});
});
})();
//]]>
</script>
</body>
</html>
So aside from probably missing a closing </div> I'm still wondering why my embedded CSS is not working.
Looking at the generated HTML code (i.e., code as modified by JavaScript) of the demo page suggests that style elements are generated inside body. Although such elements are allowed by HTML5 drafts when the scoped attribute is present, support to that attribute seems to be nonexistent, and the style sheet is applied globally. It is possible however that some browsers do not apply it at all, at least when the style element is dynamically generated.
A better approach is to make all style sheets global to the document, preferably as external style sheets, and use contextual selectors to limit the rules to some elements only. And possibly using JavaScript to change classes of elements, rather than manipulating style sheets directly.
Ok. Ugly workaround:
In the inline section, set this:
<style>
.el {width: 1px;}
</style>
In the page, set hide an element el like this:
// ui-hidden-accessible is a JQM class, moving the item out of view
// since it uses pos:absolute, is needed to not break
// selects on the page (compare to JQM ui-icon)
<span class="el ui-hidden-accessible"> </span>
Then check for the width when running inline Javascript (which works) and require the inline CSS as a separate file, when the width is not at 1px
// fallback for old devices which cannot load <style> css
// gadget is my iframe-look-a-like
if (gadget.dom.find(".el").css('width') !== "1px") {
require(['text!../css/translate.css'], function (t) {
var x = '<style>'+t+'</style>';
gadget.dom.append(x);
});
}
Ugly and an extra HTTP request, but at least the CSS is working then.

How to hide certain html that is not surrounded by <noscript> tags if javascript is disabled?

<html>
<head>
<script type="text/javascript">
// jquery and javascript functions
</script>
</head>
<body>
<fancy-jquery-ajaxy-html-section>
</fancy-jquery-ajaxy-html-section>
<noscript>
sorry you came to the wrong place - this site is all jquery/ajaxy stuff.
</noscript>
</body>
</html>
I tried surrounding <fancy-jquery-ajaxy-html> with a <script type="text/javascript"></script> but then nothing from that section is displayed even for users with javascript enabled.
But what I want to do is hide that <fancy-jquery-ajax-html> section only if the user doesn't have javascript enabled.
It contains content that is useless to someone without javascript turned on, so it shouldn't be shown at all.
A user with javascript disabled should only see a message saying that the page can't be viewed without javascript.
Is there a way do that?
The easiest way is to hide the section with CSS (e.g. display:none), then show it through Javascript.
EDIT: just a little example
<div>Everyone sees this div</div>
<div id="mydiv" class="hidden">You see this div only with JS enabled</div>
<script type="text/javascript">
$("#mydiv").removeClass("hidden");
</script>
<noscript>
<div>You will see this div only with JS disabled</div>
</noscript>
And, of course, in your CSS:
.hidden
{
display: none;
}
You could hide your fancy section using css:
<div id="fancy_jquery_ajax" style="display: none;">
</div>
then you could use use JavaScript to display the element:
$("#fancy_jquery_ajax").css("display", "block");
I hope that's right, I actually don't use jQuery that much. :S
Another approach would be to generate that HTML using JavaScript, so it can't appear unless JavaScript is running.
What I did is to have my javascript hide the nojsdiv and show maindiv. This way, if you don't have javascript the message shows up.
<body onload="allowlogin()">
<div id="maindiv" style="visibility: hidden;">
...
</div>
<div id="nojsdiv">
The training system requires javascript to be enabled.
</div>
</body>
I prefer to add a class of .js to html tags as soon as jQuery has loaded. This allows my to write css rules that apply only when the user has javascript enabled/disabled. This keeps your show and hide code out of our JS and lets CSS do its job and style the page
Here's how I would approach your problem:
<html>
<head>
<style type="text/css">
.js #fancy_jquery_ajax {display: none;}
</style>
<script type="text/javascript" src="/scripts/jquery.js"></script>
<script type="text/javascript">
$('html').addClass('js');
$(document).ready(function() {
// Stuff to do as soon as the DOM is ready
});
</script>
</head>
<body>
<div id = "fancy_jquery_ajax"></div>
<noscript><!-- stuff to say if use had javascript disabled --></noscript>
</body>
</html>
It's important to note that we want to add the class of .js as soon as jQuery has loaded and not add it in our document.ready handler. Otherwise we'd be back to square one.

Categories

Resources