- JavaScript Where To
- Example
- JavaScript Functions and Events
- Example
- Demo JavaScript in Head
- Example
- Demo JavaScript in Body
- External JavaScript
- External file: myScript.js
- Example
- External JavaScript Advantages
- Example
- External References
- Example
- Example
- Example
- How to Insert a DIV Block and Other HTML Elements into a Web Page Using JavaScript
- Prerequisites
- Adding a DIV Block or Other HTML Elements with JavaScript
- Explanation of the Code
- Demo
- Compatibility
- thesitewizard™ News Feed (RSS Site Feed)
- Please Do Not Reprint This Article
- Related Articles
- New Articles
- Popular Articles
- How to Link to This Page
- Блоки в JavaScript
- Как создать блок кода в JavaScript?
- Чем может быть полезен блок?
- Недостатки
- Style display Property
- Browser Support
- Syntax
- Property Values
- Technical Details
- More Examples
- Example
- Example
- Example
- Example
JavaScript Where To
In HTML, JavaScript code is inserted between tags.
Example
Old JavaScript examples may use a type attribute: .
The type attribute is not required. JavaScript is the default scripting language in HTML.
JavaScript Functions and Events
A JavaScript function is a block of JavaScript code, that can be executed when «called» for.
For example, a function can be called when an event occurs, like when the user clicks a button.
You will learn much more about functions and events in later chapters.
JavaScript in or
You can place any number of scripts in an HTML document.
Scripts can be placed in the , or in the section of an HTML page, or in both.
JavaScript in
In this example, a JavaScript function is placed in the section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
Demo JavaScript in Head
JavaScript in
In this example, a JavaScript function is placed in the section of an HTML page.
The function is invoked (called) when a button is clicked:
Example
Demo JavaScript in Body
Placing scripts at the bottom of the element improves the display speed, because script interpretation slows down the display.
External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a tag:
Example
You can place an external script reference in or as you like.
The script will behave as if it was located exactly where the tag is located.
External scripts cannot contain tags.
External JavaScript Advantages
Placing scripts in external files has some advantages:
- It separates HTML and code
- It makes HTML and JavaScript easier to read and maintain
- Cached JavaScript files can speed up page loads
To add several script files to one page — use several script tags:
Example
External References
An external script can be referenced in 3 different ways:
- With a full URL (a full web address)
- With a file path (like /js/)
- Without any path
This example uses a full URL to link to myScript.js:
Example
This example uses a file path to link to myScript.js:
Example
This example uses no path to link to myScript.js:
Example
You can read more about file paths in the chapter HTML File Paths.
How to Insert a DIV Block and Other HTML Elements into a Web Page Using JavaScript
I was asked by a visitor how he could programmatically insert a DIV block into his web page using JavaScript. This article shows one way in which this can be done. The method given can also be used for other HTML elements.
Prerequisites
I will assume here that you know some JavaScript and HTML. You do not have to be an expert or anything like that, but some knowledge is needed, otherwise even the question dealt with here will be meaningless to you.
If you do not have a website, and have arrived here thinking that this article will give you an idea of what web development is like, please read How to Create a Website or my articles on domain names instead, since they will be more relevant.
Adding a DIV Block or Other HTML Elements with JavaScript
The following code demonstrates one way to insert a DIV block with JavaScript.
var block_to_insert ;
var container_block ;
block_to_insert = document.createElement( ‘div’ );
block_to_insert.innerHTML = ‘This demo DIV block was inserted into the page using JavaScript.’ ;
container_block = document.getElementById( ‘democontainer’ );
container_block.appendChild( block_to_insert );
Let’s say that the relevant part of the web page has the following HTML.
The new block will appear below this paragraph.
When the code is executed, that part of the page effectively becomes as follows.
The new block will appear below this paragraph.
Explanation of the Code
Let’s work through the code, line by line.
The above line sets the content of the DIV block so that it has the words «This demo DIV block was inserted into the page using JavaScript.» It is equivalent to writing the following HTML code.
The above is the bare minimum that you will typically need to do to inject a DIV block into a web page. You will probably need to add additional code, such as to assign your DIV an id and/or class so that you can customize its appearance using CSS, for example, as follows:
Demo
You can see a demo of the code in action by clicking the button below. The same code given above is used here. The outline around the DIV block was added using CSS.
Compatibility
The above code should work in all modern browsers.
Copyright © 2017 Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.
thesitewizard™ News Feed (RSS Site Feed)
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
Please Do Not Reprint This Article
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
Related Articles
New Articles
Popular Articles
How to Link to This Page
It will appear on your page as:
Copyright © 2017 Christopher Heng. All rights reserved.
thesitewizard™, thefreecountry™ and HowToHaven™ are trademarks of Christopher Heng.
This page was last updated on 19 May 2017.
Блоки в JavaScript
В сей поздний час мою голову посетила одна очень странная мысль. Не долго думая, я решил написать коротенький пост по этому поводу.
Что же, сил и времени на написание второй статьи о WebRTC у меня до сих пор нет, а на пост-заметку я решил все же найти мозговые и временные ресурсы.
Суть мысли, или даже вопроса — почему никто (встречавшийся мне) не использует отдельные блоки кода (помимо тех, которые используются с выражениями if else и т.д.) в своих JavaScript приложениях?
Как создать блок кода в JavaScript?
Чем может быть полезен блок?
В JavaScript блоки кода не создают свою область видимости (скоуп), поэтому будем искать полезность в чем-то другом.
Самое элементарное применение — разделение логических частей кода. Да еще какое! Блок можно использовать с меткой.
Толку с нее в данной ситуации мало. С таким успехом можно заменить метку на комментарий, но ведь как красиво смотрится.
Но остается проблема в ограниченности метки.
Опытный и не очень программист может сказать — все логичные блоки / части кода лучше выносить в отдельные функции. Но попробую сразу же не согласиться. Давайте рассмотрим пример из жизни?
Допустим, есть у меня Backbone приложение. При инициализации каждой view я должен совершать стандартные действия: подписываться на глобальные события, подписываться на изменения модели или коллекции и т.д.
Почему-то я не хочу выносить это в отдельные функции. Я привык, что в методе initialize я могу увидеть сразу подписку на все нужные события.
Так почему же мне не разделить эту массу кода на отдельные логические блоки кода в рамках одного метода и скоупа?
Backbone.View.extend( < initialize: function () < ModelEvents: < this.model.on('change', this.render); this.model.on('add', this.onAdd); this.model.on('change:type', this.onResetType); >AppEvents: < app.subscribe('reload', this.render, this); app.subscribe('remove', this.remove, this); app.subscribe('vodka', this.drink, this); >> >);
Недостатки
Даже не знаю, какие могут быть недостатки у такого способа разделения кода. Быть может, есть вероятность того, что можно запутаться — перепутать блок кода с объектом. Но у меня такой наклонности не возникает.
Вывод: использовать такие блоки — дело выбора каждого. Комментарии, блоки — кому как нравится. Но хотелось бы все же найти интересное применение таким блокам.
Style display Property
The display property sets or returns the element’s display type.
Elements in HTML are mostly «inline» or «block» elements: An inline element has floating content on its left and right side. A block element fills the entire line, and nothing can be displayed on its left or right side.
The display property also allows the author to show or hide an element. It is similar to the visibility property. However, if you set display:none , it hides the entire element, while visibility:hidden means that the contents of the element will be invisible, but the element stays in its original position and size.
Tip: If an element is a block element, its display type can also be changed with the float property.
Browser Support
Syntax
Return the display property:
Property Values
Value | Description | ||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
block | Element is rendered as a block-level element | ||||||||||||||||||||||||||||||||||||||
compact | Element is rendered as a block-level or inline element. Depends on context | ||||||||||||||||||||||||||||||||||||||
flex | Element is rendered as a block-level flex box. New in CSS3 | ||||||||||||||||||||||||||||||||||||||
inline | Element is rendered as an inline element. This is default | ||||||||||||||||||||||||||||||||||||||
inline-block | Element is rendered as a block box inside an inline box | ||||||||||||||||||||||||||||||||||||||
inline-flex | Element is rendered as a inline-level flex box. New in CSS3 | ||||||||||||||||||||||||||||||||||||||
inline-table | Element is rendered as an inline table (like
|