Javascript hide all text

Using Javascript and/or CSS

This page was created as a result of a puzzle to deal with the still-used but ancient browser NS4. More and more people don’t want to bother taking the time to deal with this obsolete browser. But even if you don’t care whether or not NS4 can handle your webpages, you may find something useful here describing two different ways that can be used to hide and show text in an HTML file by using Javascript and/or CSS.

Warning! I am not an expert in Javascript or CSS. But the following instructions using relatively simple coding do work for me. This method will get you started with javascripting and/or CSS. It should display in all the later browsers and most of the earlier ones.

Text

Hiding and/or showing text with CSS

To hide and/or show text with CSS, you must create two different stylesheets. For this example, you will see style.css and style_insert.css. Of course, your .css files can be named anything you want.

If you look at the source code of this page, you will see that there are 2 sentences below. The first sentence will appear only in NS4 and browsers with CSS disabled. The second sentence will appear only in current browsers and any browser with CSS disabled. The second half of the second sentence will only appear in NS4 with javascript disabled. Only those with CSS disabled will see all three phrases in their entirety.

This class=»ns4″ sentence should only show up in browsers with CSS disabled and NS4.

This class=»later» sentence should only show up in current browsers.

. and NS4 with javascript (and CSS) disabled.

how style.css looks:

@import url(style_insert.css);
.ns4 >
.later < display:none; >
[rest of styles follow. ]

how style_insert.css looks:

You can safely change the sections that are in bold text in the above example. The stylesheet that is called for in is the stylesheet that is for the more ancient browser. The stylesheet that is called for by the @import url is for current browsers. It is essential that the @import url be placed on the first line of your main stylesheet. Also make sure that your class names remain in the same order in the two stylesheets. Note the !important that appears beside the two show/hide styles in the stylesheet to be read by current browsers. This is because the majority of your viewers will be using more recent browsers.

Читайте также:  Frame class methods in java

Hiding and/or showing text with Javascript

Perhaps you would also like to hide text from all browsers with javascript disabled. To do that, you can use document.write . To show text to browsers with javascript disabled, you can use and

If you look at the source code of this page, you will see that there are 2 sentences below. The first sentence will appear only in browsers with javascript enabled. The second sentence will appear only browsers with javascript disabled.

Copy the following section and paste it below in your HTML file.

You can safely change the sections that are in bold text. Note that you can place different text for browsers with javascript disabled (indeed, this is often desirable). This is done in the section.

Escaping Characters in Javascript

As you may have noticed from looking at the above example, the HTML after document.write looks slightly different than it does normally. This is because the characters «(quotation mark), (single quote) and /(forward slash) are integral to the javascript code itself. So depending on how your javascript is constructed, at least two of these characters must be escaped when used in a javascript. To do that, a \ (backward slash) is placed before each of the aforementioned characters. Without these backward slashes, there is a very high likelihood that your script will not appear at all.

If you wish to display «(quotation marks) after document.write , precede the character with \ (backward slash). Or you can also use the character entity rather than the character itself. For instance, if you want to display the sentence

Murphy’s Law states, «Everything that can go wrong will go wrong.»

You would type the following inside your script tags:

document.write(«

Murphy’s Law states, \«Everything that can go wrong will go wrong.\«\/p>»);

code:
document.write(«

Murphy’s Law states, "Everything that can go wrong will go wrong."\/p>»);

Another way to get around this problem is to always use single quote marks to surround the document.write text. However, in that case, then all instances of (single quote) would have to be escaped. They can either be preceded by the \ (backward slash) or replaced with ' . And the / (forward slash) will still have to be escaped:

document.write(‘

Murphy\‘s Law states: «Everything that can go wrong will go wrong.»\/p>’);

code:
document.write(‘

Murphy's Law states: «Everything that can go wrong will go wrong.»\/p>’);

No matter how you look at it, unless you avoid the use of the characters , « and / completely, some escaping of characters may be required in your document.write text area. Please read more about character entities here.

To display the following phrase and link with javascript, use document.write . A different message is displayed when javascript is disabled.

You can safely change whatever parts are in bold text in the above example. Whatever is typed after document.write must remain on the same line of coding (ie: no line breaks). Also, remember to escape any characters that are integral to the javascript code. Otherwise, your script will most probably not appear anywhere.

Читайте также:  Условные комментарии

If nothing is put between , or if the noscript tag is left out altogether, nothing will show in a browser with javascript disabled.

CSS/Javascript Text

There are five sentences in the source code. The first three will appear only to those browsers with javascript enabled. The fourth will appear in browsers with javascript disabled and the second half of the fourth will also appear in all browsers with javascript disabled. The fifth will appear only in ancient browsers with javascript disabled. To display the text, document.write and are used.

You can safely change whatever parts are in bold text in the above example. Whatever is typed after document.write must remain on the same line of coding (ie: no line breaks). Also, remember to escape any characters that are integral to the javascript code. Otherwise, your script will most probably not appear anywhere.

The reason that class=»later» phrases show up in ancient browsers with javascript disabled is because the people who designed those browsers inexplicably intertwined CSS and javascript. In the ancient browser, if javascript is disabled, so is CSS. This is just one of the many many reasons that you really should upgrade your browser.

Remember, if nothing is typed between , or if the noscript tag is left out altogether, nothing at all will show in any browser with javascript disabled.

Confused? For more detailed and much better instructions, please go to JavaScript Kit, JavaScript tutorial — The W3C DOM and/or W3Schools Javascript Tutorial. Free javascripts are available from The Javascript Source, Dynamic Drive and JavaScript Resources!as well as many others.

Источник

fotinakis / hide-text.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

function textNodesUnder ( el )
var n , a = [ ] ;
var walk = document . createTreeWalker ( el , NodeFilter . SHOW_TEXT , null , false ) ;
while ( n = walk . nextNode ( ) )
return a ;
>
// Normalize all text nodes (merge adjacent nodes).
var elements = document . getElementsByTagName ( ‘*’ ) ;
for ( var i = 0 ; i < elements . length ; i ++ )
elements [ i ] . normalize ( ) ;
>
elements = textNodesUnder ( document . getElementsByTagName ( ‘body’ ) [ 0 ] ) ;
for ( var i = 0 ; i < elements . length ; i ++ )
// Skip empty nodes.
if ( elements [ i ] . nodeValue . trim ( ) == » )
// Create a wrapper span with opacity: 0 and replace the current textNode.
var wrapperSpan = document . createElement ( ‘span’ ) ;
wrapperSpan . setAttribute ( ‘style’ , ‘opacity: 0’ ) ;
wrapperSpan . appendChild ( elements [ i ] . cloneNode ( ) ) ;
elements [ i ] . parentNode . replaceChild ( wrapperSpan , elements [ i ] ) ;
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// Or, in jQuery:
$ ( ‘*’ ) . contents ( ) . filter ( function ( i , node )
return node . nodeType === 3 && node . textContent . trim ( ) !== » ;
> ) . wrap ( ‘ ‘ ) ;

Источник

Скрыть / показать элементы JavaScript

Скрыть / показать элементы JavaScript

  1. Используйте свойство style.visibility , чтобы скрыть / показать элементы HTML
  2. Используйте свойство style.display , чтобы скрыть / показать элементы HTML
  3. Используйте jQuery hide() / show() , чтобы скрыть / показать элементы HTML
  4. Используйте jQuery toggle() , чтобы скрыть / показать элементы HTML
  5. Используйте addClass() / removeClass() , чтобы скрыть / показать элементы HTML

Мы часто сталкиваемся с ситуациями, когда мы хотим переключиться между отображением и скрытием элемента. В этом руководстве рассказывается, как скрыть / отобразить элемент в JavaScript.

Используйте свойство style.visibility , чтобы скрыть / показать элементы HTML

Свойство style.visibility , когда установлено значение hidden, делает целевой элемент скрытым, но не удаляет его из потока. Итак, целевой элемент отображается, но не отображается. Это не влияет на планировку и позволяет другим элементам занимать свое естественное пространство. Мы можем снова сделать целевой элемент видимым, вернув для свойства значение visible .

document.getElementById(id).style.visibility = "visible"; // show  document.getElementById(id).style.visibility = "hidden"; // hide 

Используйте свойство style.display , чтобы скрыть / показать элементы HTML

Свойство style.display , когда установлено в none , удаляет целевой элемент из обычного потока страницы и позволяет остальным элементам занимать его пространство. Хотя целевой элемент не отображается на странице, мы все равно можем взаимодействовать с ним через DOM. Затрагиваются все потомки, и они не отображаются так же, как родительский элемент. Мы можем снова сделать целевой элемент видимым, установив для свойства значение block . Желательно установить display как » , потому что block добавляет поле к элементу.

document.getElementById(id).style.display = 'none'; // hide  document.getElementById(id).style.display = ''; // show 

Используйте jQuery hide() / show() , чтобы скрыть / показать элементы HTML

  1. Скорость : определяет скорость задержки эффекта затухания.
  2. Замедление : определяет функцию замедления, используемую для перехода в видимое / скрытое состояние. Принимает два разных значения: свинг и линейный .
  3. Обратный вызов : это функция, выполняемая после завершения выполнения метода show() .

Точно так же метод jQuery hide() помогает скрыть выбранные элементы. Принимает те же 3 параметра, что и show() .

$("#element").hide(); // hide  $("#element").show(); // show 

Используйте jQuery toggle() , чтобы скрыть / показать элементы HTML

JQuery toggle() — это специальный метод, который позволяет нам переключаться между методами hide() и show() . Это помогает сделать скрытые элементы видимыми, а видимые — скрытыми. Он также принимает те же три параметра, что и методы jQuery hide() и show() . Также требуется отображение 4-го параметра, которое помогает переключать эффект скрытия / отображения. Это логический параметр, который при значении false скрывает элемент.

$("div.d1").toggle(500,swing); // toggle hide and show 

Используйте addClass() / removeClass() , чтобы скрыть / показать элементы HTML

Функция addClass() помогает нам добавить класс в существующий список классов элемента, а removeClass() помогает нам удалить его. Мы можем использовать эти функции для переключения скрытия / отображения, написав собственный класс, скрывающий элемент, а затем добавив и удалив его из списка классов.

.hidden :none> $("div").addClass("hidden"); // hide  $("div").removeClass("hidden"); // show 

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

Сопутствующая статья — JavaScript DOM

Источник

Оцените статью