Vitalij
Vitalij

Reputation: 680

Some templates in Javascript

How do I create a second logical structure with Javascript.

Is a webpage, and when it's loading (DOM fully don't ready yet) is executing javascipt code where:

<script>
if(window.innerWidth>900){

 /* show huge HTML with javascript stuff here */

} else {

 /* show huge HTML with javascript stuff here */

}
</script>

I want have something similar with second code example in PHP language:

<? if(true){ ?>
/* show huge HTML with javascript stuff here */
<? } else { ?>
/* show huge HTML with javascript stuff here */
<? } ?>

I need possibility to have different javascript code with html on initialising window width, when page loads.

Upvotes: 0

Views: 241

Answers (3)

Roman
Roman

Reputation: 6428

Following my intuition, I guess you want to template the page based on screen / window size. Showing a different layout based on how large the screen is... And you want this to be "dynamic" (I hate that word), I mean updated in real-time.

This is generally called "Responsive Design" and is done in a somewhat different way. You rely (if possible only) on different CSS Stylesheets that are specific to different window sizes. Use stylesheet A for screensize X and stylesheet B for screensize Y, etc...

This is achieved by using media queries.

Of course this requires you to have clean and semantic HTML code (you know... no table layouts, etc...).

Some examples of sites that use responsive design: link (go on those sites and resize your browser window)

Upvotes: 0

Kai Mattern
Kai Mattern

Reputation: 3085

That is not the way JS works. You could of course print the html inline here, but this will create a hell of a mess in your code. I would strongly discourage this. If you need this kind of templating capabilities, you are better off using some templating engine.

For example there is EJS, which allows you to write separate html templates with JS includied. Basically you load the template, pass your data to it, render the html and insert it into the DOM tree. This allows you to keep your code pretty clean.

http://embeddedjs.com/

Upvotes: 1

zackg
zackg

Reputation: 329

Vanilla Javascript isn't going to provide you those kind of templating features, unfortunately. However, there are many libraries that exist for this purpose. You might want to check out this page for some links.

Upvotes: 1

Related Questions