Jesus, eu preciso do Senhor. Abro a porta da minha vida e O recebo como meu Salvador e Senhor. Obrigado por ter morrido na cruz para perdoar meus pecados, por me dar a vida eterna, e por me aceitar como eu sou. Toma conta da minha vida e faça de mim a pessoa que deseja que eu seja. Amém
Ó Mulher! Como és fraca e como és forte!Como sabes ser doce e desgraçada!Como sabes fingir quando em teu peitoA tua alma se estorce amargurada!Quantas morrem saudosa duma imagem.Adorada que amaram doidamente!Quantas e quantas almas endoidecemEnquanto a boca rir alegremente!Quanta paixão e amor às vezes têmSem nunca o confessarem a ninguémDoce alma de dor e sofrimento!Paixão que faria a felicidade.Dum rei; amor de sonho e de saudade,Que se esvai e que foge num lamento!Florbela Espanca
ANGÚSTIA
Tortura do pensar! Triste lamento!Quem nos dera calar a tua voz!Quem nos dera cá dentro, muito a sós,Estrangular a hidra num momento!E não se quer pensar! ... e o pensamentoSempre a morder-nos bem, dentro de nós ...Querer apagar no céu – ó sonho atroz! –O brilho duma estrela, com o vento! ...E não se apaga, não ... nada se apaga!Vem sempre rastejando como a vaga ...Vem sempre perguntando: “O que te resta? ...”Ah! não ser mais que o vago, o infinito!Ser pedaço de gelo, ser granito,Ser rugido de tigre na floresta!Florbela Espanca, em "Livro de Mágoas"
CONTO DE FADAS
Eu trago-te nas mãos o esquecimentoDas horas más que tens vivido, Amor!E para as tuas chagas o unguentoCom que sarei a minha própria dor.Os meus gestos são ondas de Sorrento...Trago no nome as letras de uma flor...Foi dos meus olhos garços que um pintorTirou a luz para pintar o vento...Dou-te o que tenho: o astro que dormita,O manto dos crepúsculos da tarde,O sol que é d'oiro, a onda que palpita.Dou-te comigo o mundo que Deus fez!- Eu sou Aquela de quem tens saudade,A Princesa do conto: “Era uma vez...”Florbela Espanca, em "Charneca em Flor"
DE JOELHOS
“Bendita seja a Mãe que te gerou.”Bendito o leite que te fez crescerBendito o berço aonde te embalouA tua ama, pra te adormecer!Bendita essa canção que acalentouDa tua vida o doce alvorecer ...Bendita seja a Lua, que inundouDe luz, a Terra, só para te ver ...Benditos sejam todos que te amarem,As que em volta de ti ajoelharemNuma grande paixão fervente e louca!E se mais que eu, um dia, te quiserAlguém, bendita seja essa Mulher,Bendito seja o beijo dessa boca!!Florbela Espanca, em "Livro de Mágoas"
EU
Eu sou a que no mundo anda perdida,Eu sou a que na vida não tem norte,Sou a irmã do Sonho,e desta sorteSou a crucificada … a dolorida …Sombra de névoa tênue e esvaecida,E que o destino amargo, triste e forte,Impele brutalmente para a morte!Alma de luto sempre incompreendida!…Sou aquela que passa e ninguém vê…Sou a que chamam triste sem o ser…Sou a que chora sem saber porquê…Sou talvez a visão que Alguém sonhou,Alguém que veio ao mundo pra me ver,E que nunca na vida me encontrou!Florbela Espanca
IMPOSSÍVEL
Disseram-me hoje, assim, ao ver-me triste:“Parece Sexta-Feira de Paixão.Sempre a cismar, cismar de olhos no chão,Sempre a pensar na dor que não existe ...O que é que tem?! Tão nova e sempre triste!Faça por estar contente! Pois então?! ...”Quando se sofre, o que se diz é vão ...Meu coração, tudo, calado, ouviste ...Os meus males ninguém mos adivinha ...A minha Dor não fala, anda sozinha ...Dissesse ela o que sente! Ai quem me dera! ...Os males de Anto toda a gente os sabe!Os meus ... ninguém ... A minha Dor não cabeNos cem milhões de versos que eu fizera! ...Florbela Espanca
MINHA CULPA
A Artur LedesmaSei lá! Sei lá! Eu sei lá bemQuem sou?! Um fogo-fátuo, uma miragem...Sou um reflexo... um canto de paisagemOu apenas cenário! Um vaivém...Como a sorte: hoje aqui, depois além!Sei lá quem Sou?! Sei lá! Sou a roupagemDum doido que partiu numa romagemE nunca mais voltou! Eu sei lá quem!...Sou um verme que um dia quis ser astro...Uma estátua truncada de alabastro...Uma chaga sangrenta do Senhor...Sei lá quem sou?! Sei lá! Cumprindo os fados,Num mundo de vaidades e pecados,Sou mais um mau, sou mais um pecador...Florbela Espanca, em "Charneca em Flor"
O MEU ORGULHO
Lembro-me o que fui dantes. Quem me deraNão me lembrar! Em tardes dolorosasLembro-me que fui a PrimaveraQue em muros velhos faz nascer as rosas!As minhas mãos outrora carinhosasPairavam como pombas... Quem souberaPorque tudo passou e foi quimera,E porque os muros velhos não dão rosas!O que eu mais amo é que mais me esquece...E eu sonho: "Quem olvida não merece..."E já não fico tão abandonada!Sinto que valho mais, mais pobrezinha:Que também é orgulho ser sozinha,E também é nobreza não ter nada!Florbela Espanca, em "Livro de Sóror Saudade"
ÓDIO?
Ódio por Ele? Não... Se o amei tanto,Se tanto bem lhe quis no meu passado,Se o encontrei depois de o ter sonhado,Se à vida assim roubei todo o encanto,Que importa se mentiu? E se hoje o prantoTurva o meu triste olhar, marmorizado,Olhar de monja, trágico, geladoCom um soturno e enorme Campo Santo!Nunca mais o amar já é bastante!Quero senti-lo doutra, bem distante,Como se fora meu, calma e serena!Ódio seria em mim saudade infinda,Mágoa de o ter perdido, amor ainda!Ódio por Ele? Não... não vale a pena...Florbela Espanca, em "Livro de Sóror Saudade"
SER POETA
Ser Poeta é ser mais alto, é ser maiorDo que os homens! Morder como quem beija!É ser mendigo e dar como quem sejaRei do Reino de Aquém e de Além Dor!É ter de mil desejos o esplendorE não saber sequer que se deseja!É ter cá dentro um astro que flameja,É ter garras e asas de condor!É ter fome, é ter sede de Infinito!Por elmo, as manhãs de oiro e de cetim...É condensar o mundo num só grito!E é amar-te, assim, perdidamente...É seres alma e sangue e vida em mimE dizê-lo cantando a toda gente!Florbela Espanca, em "Charneca em Flor"
TÉDIO
Passo pálida e triste. Oiço dizer:“Que branca que ela é! Parece morta!”e eu que vou sonhando, vaga, absorta,não tenho um gesto, ou um olhar sequer ...Que diga o mundo e a gente o que quiser!– O que é que isso me faz? O que me importa? ...O frio que trago dentro gela e cortaTudo que é sonho e graça na mulher!O que é que me importa?! Essa tristezaÉ menos dor intensa que frieza,É um tédio profundo de viver!E é tudo sempre o mesmo, eternamente ...O mesmo lago plácido, dormente ...E os dias, sempre os mesmos, a correr ...Florbela Espanca, em "Livro de Mágoas"
SEM REMÉDIO
Aqueles que me têm muito amorNão sabem o que sinto e o que sou ...Não sabem que passou, um dia, a DorÀ minha porta e, nesse dia, entrou.E é desde então que eu sinto este pavor,Este frio que anda em mim, e que gelouO que de bom me deu Nosso Senhor!Se eu nem sei por onde ando e onde vou!!Sinto os passos da Dor, essa cadênciaQue é já tortura infinda, que é demência!Que é já vontade doida de gritar!E é sempre a mesma mágoa, o mesmo tédio,A mesma angústia funda, sem remédio,Andando atrás de mim, sem me largar!Florbela Espanca, em "Livro de Mágoas"
VOLÚPIA
No divino impudor da mocidade,Nesse êxtase pagão que vence a sorte,Num frêmito vibrante de ansiedade,Dou-te o meu corpo prometido à morte!A sombra entre a mentira e a verdade...A nuvem que arrastou o vento norte...- Meu corpo! Trago nele um vinho forte:Meus beijos de volúpia e de maldade!Trago dálias vermelhas no regaço...São os dedos do sol quando te abraço,Cravados no teu peito como lanças!E do meu corpo os leves arabescosVão-te envolvendo em círculos dantescosFelinamente, em voluptuosas danças...Florbela Espanca, em "Charneca em Flor"
FANATISMO
Minh'alma, de sonhar-te, anda perdida.Meus olhos andam cegos de te ver.Não és sequer razão do meu viverPois que tu és já toda a minha vida!Não vejo nada assim enlouquecida...Passo no mundo, meu Amor, a lerNo mist'rioso livro do teu serA mesma história tantas vezes lida!..."Tudo no mundo é frágil, tudo passa...Quando me dizem isto, toda a graçaDuma boca divina fala em mim!E, olhos postos em ti, digo de rastros:"Ah! podem voar mundos, morrer astros,Que tu és como Deus: princípio e fim!..."Florbela Espanca, em "Livro de Sóror Saudade"
AMAR!
Eu quero amar, amar perdidamente!Amar só por amar: Aqui... além...Mais Este e Aquele, o Outro e toda a gente...Amar! Amar! E não amar ninguém!Recordar? Esquecer? Indiferente!...Prender ou desprender? É mal? É bem?Quem disser que se pode amar alguémDurante a vida inteira é porque mente!Há uma Primavera em cada vida:É preciso cantá-la assim florida,Pois se Deus nos deu voz, foi pra cantar!E se um dia hei de ser pó, cinza e nadaQue seja a minha noite uma alvorada,Que me saiba perder... pra me encontrar...Florbela Espanca, em "Charneca em Flor"
ÁRVORES DO ALENTEJO
Horas mortas... Curvada aos pés do Monte
A planície é um brasido... e, torturadas,
As árvores sangrentas, revoltadas,
Gritam a Deus a bênção duma fonte!E quando, manhã alta, o sol posponte
A oiro a giesta, a arder, pelas estradas,
Esfíngicas, recortam desgrenhadas
Os trágicos perfis no horizonte!
Árvores! Corações, almas que choram,
Almas iguais à minha, almas que imploram
Em vão remédio para tanta mágoa!
Árvores! Não choreis! Olhai e vede:- Também ando a gritar, morta de sede,
Pedindo a Deus a minha gota de água!Florbela Espanca
AMIGA
Deixa-me ser a tua amiga, Amor;
A tua amiga só, já que não queres
Que pelo teu amor seja a melhor
A mais triste de todas as mulheres.
Que só, de ti, me venha mágoa e dor
O que me importa a mim?! O que quiseres
É sempre um sonho bom! Seja o que for,
Bendito sejas tu por mo dizeres!Beija-me as mãos, Amor, devagarinho...
Como se os dois nascêssemos irmãos,
Aves cantando, ao sol, no mesmo ninho...Beija-mas bem!... Que fantasia louca
Guardar assim, fechados, nestas mãos
Os beijos que sonhei pra minha boca!...Florbela Espanca
In this tutorial, we will see various JavaScript examples. you can also download JavaScript examples pdf for free.
If you are a web developer then you should know what is JavaScript and how to use JavaScript in various web applications.
I hope the below examples will be helpful to you, to learn JavaScript. So let’s start with various javascript examples.
Table of Contents
What is JavaScript?
JavaScript is a lightweight object-based scripting programing language. Basically to add the functionality in HTML code javascript is used. Because of the JavaScript, web pages become more interactive with the user.
Mostly JavaScript use for game development and mobile application development. JavaScript makes the HTML form dynamic. JavaScript is used to create client-side dynamic pages.
We can run JavaScript with the help of any browser. We can use the Javascript code in the HTML file using the Script tag. When we run the HTML code in the browser then the javascript also runs.
The main advantage of JavaScript scripting language is all browsers like IE, Chrome, Mozilla, Opera, etc supports JavaScript. JavaScript runs on any operating system like Windows, Linux, mac anything.
Editors For JavaScript
Before knowing, how to start with JavaScript, we have to know what are the available editors for JavaScript. Some of the recommend editors for JavaScript are:
Before start writing your first JavaScript code, Few things you should remember on how to start with JavaScript.
We need to put JavaScript code inside <script> and </script> tags.
Example:
<script>
alert("Welcome to Top 51 JavaScript Examples You Should Learn");
</script>
We can put any number of scripts inside an HTML document, either in the <body> or <head> section of the HTML page or in both tags.
<!DOCTYPE html>
<html>
<head>
<script>
function demoFunction() {
alert("JavaScript Examples")
}
</script>
</head>
<body>
<p>Demo JavaScript Examples</p>
<button type="button" id="btnDemo" onclick="myFunction()">Download It Now</button>
<p>Welcome to Top 51 JavaScript Examples You Should Learn PDF</p>
<button type="button" id="btnSubmit" onclick="myFunction()">Download It Now</button>
<script>
function myFunction() {
alert("JavaScript Examples PDF Download")
}
</script>
</body>
</html>
We can also store JavaScript code in an external .js file and call that file inside our HTML Code. We should not write all JavaScript code inside the HTML file.
We can store below script code inside a .js file like (51JavaScriptExamples.js)
function showAlert() {
alert (Welcome to 51 JavaScript examples tutorial);
}
In the below example, We can show an alert in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Example: Display alert in javascript</p>
<p>Give Your Details</p>
First name:<br>
<input type="text" id="txtFirstName" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="txtLastName">
<br>
<br>
<button onclick="showAlert()" id=btnSubmit>Submit</button>
<script>
function showAlert() {
alert("Created Account");
}
</script>
</body>
</html>
The output: We can see in the output one alert message is coming and telling that “Created Account”
Display Conformation box using JavaScript
In the Conformation Box, one box will appear and ask for conformation like “OK” and “Cancel” option.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Top 51 JavaScript Example: Display Confirmation Box using JavaScript</p>
<button onclick="showConformationMessage()" id=btnClick>Click here to check your account is created or not </button>
<script type="text/javascript">
function showConformationMessage(){
var name = confirm("Are you want to use the account");
if (name == true){
alert(" Account created sucessfully");
}
else{
alert("sorry,try again Your account is not created");
}
}
</script>
</body>
</html>
Output:
The output is showing a confirmation box which is asking for “Are you want to use the account”. We can click on “Ok” or “Cancel”
Display Prompt box using JavaScript
Prompt box in JavaScript allows user to input in a textbox. Here we will see how we can show a prompt box using JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Examples: Display Prompted box using JavaScript</p>
<button onclick="showPromptBox()">Click here to see prompt box</button>
<p id="pId"></p>
<script>
function showPromptBox() {
var text;
var username = prompt("Please enter your username", "");
if (username == null || username == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello !" + username + "Welcome to your SharePoint site";
}
document.getElementById("pId").innerHTML =text;
}
</script>
</body>
</html>
Output:
When click on OK we can able to see below output.
Example-2: mouseover and mouseout in javascript
This example shows how we can use onmouseover javascript functionality as well as onmouseout in javascript. Below is an example, where a user mouse over an image, it will display the large picture.
<!DOCTYPE html>
<html>
<body>
<img onmouseover="largePictureOnMouseOver(this)"onmouseout="smallPictureOnMouseOut(this)" border="0" src="https://onlysharepoint2013.sharepoint.com/:i:/r/sites/Raju/tsinfo/SiteAssets/cool-javascript-examples.jpg?csf=1&e=igNfKB" width="32" height="32">
<p>The large picture will display when mouse pointer over the image and when mouse pointer is moved out of picture</p>
<script>
function largePictureOnMouseOver(p) {
p.style.height = "64px";
p.style.width = "64px";
}
function smallPictureOnMouseOut(p) {
p.style.height = "32px";
p.style.width = "32px";
}
</script>
</body>
</html>
Similarly, in the below JavaScript example, we can use onmouseout which will display a larger picture when the user removes the mouse pointer from a picture.
<!DOCTYPE html>
<html>
<body>
<img onmouseout="largePictureOnMouseOver(this)"onmouseover="smallPictureOnMouseOut(this)" border="0" src="https://onlysharepoint2013.sharepoint.com/:i:/r/sites/Raju/tsinfo/SiteAssets/cool-javascript-examples.jpg?csf=1&e=igNfKB" width="32" height="32">
<p>The small picture will display when mouse pointer over the image and when mouse pointer is moved out of picture, large picture is displaying</p>
<script>
function largePictureOnMouseOver(p) {
p.style.height = "64px";
p.style.width = "64px";
}
function smallPictureOnMouseOut(p) {
p.style.height = "32px";
p.style.width = "32px";
}
</script>
</body>
</html>
Example-3: Use onkeypress In JavaScript to Display Alerts
By using JavaScript, we can display alert box when user press on the text box.
<!DOCTYPE html>
<html>
<body>
<p><b>OnKeyDown JavaScript Example<b></p>
<input type="text" id="txtKey"onkeydown="onKeyDown()">
<script>
function onKeyDown() {
alert("You press the down arrow key in the text box");
}
</script>
</body>
</html>
Example-4: JavaScript Validation Examples
We can validate input controls using JavaScript easily. Below are a few JavaScript validation examples.
Textbox required validation in javascript
By using JavaScript, we can validate for empty value in textboxes. Whenever an user tries to submit a form without entering a value in the textbox, it will display mandatory field validation messages in an alert box.
<html>
<body>
<script type='text/javascript'>
function textBoxValidation()
{
if(document.getElementById('txtBox').value.trim()== "")
{
alert('Textbox should not be blank');
txtBox.focus();
return false;
}
alert("Your name submitted sucessfully")
return true;
}
</script>
<form>
Name:<input type='text' id='txtBox'/> <input type='button' onclick="textBoxValidation()"id="btnSubmit" value='Submit' />
</form>
</body>
</html>
Email validation in JavaScript
The below JavaScript code validates a textbox for correct email id. Whatever user enters if not a proper email id then it will display a message in the alert box.
<html>
<p>51 example of JavaScript</p>
<body>
<script type='text/javascript'>
function emailValidation()
{
var emailIdValue= /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(document.getElementById('txtEmail').value.match(emailIdValue))
{
alert("Email Validation sucessfully");
return true;
}
else
{
alert("This email is invalid, give a proper email id");
txtEmail.focus();
return false;
}
}
</script>
<form>
Enter the E-mail Address value: <input type='text' id='txtEmail'/>
<input type='button' onclick="emailValidation()" id="btnSubmit" value='Submit' />
</form>
</body>
</html>
Letter Validation in JavaScript
There will be some scenarious where you want users to enter only letters like (A-Z or a-z), We can do letter only validations using JavaScript.
<html>
<body>
<script type='text/javascript'>
function letterValidation()
{
var letterValue = /^[a-zA-Z]+$/;
if(document.getElementById('txtletter').value.match(letterValue))
{
alert("Yes you enter letters only.");
return true;
}
else
{
alert('Enter only Letters like A-Z or a-z');
txtletter.focus();
return false;
}
}
</script>
<form>
Please Letters Only: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="letterValidation()" value='Submit' />
</form>
</body>
</html>
Number Validation in JavaScript
Sometimes, you may get business requirement where you need to allows users to enter only numbers, we can do JavaScript number validation very easily.
<html>
<body>
<script type='text/javascript'>
function onlyNumberValidation()
{
var numbers = /^[0-9]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter numbers only.");
return true;
}
else
{
alert('Only numbers are allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="onlyNumberValidation()" value='Submit' />
</form>
</body>
</html>
Letter and Number Validation in JavaScript
Sometimes, you may get business requirement where you need to allows users to enter either letter and numbers, we can validate letters and numbers by using JavaScript very easily.
<html>
<body>
<script type='text/javascript'>
function letterAndNumberValidation()
{
var letterAndNumberValue = /^[0-9a-zA-Z]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter letters or numbers only.");
return true;
}
else
{
alert('Only letters and numbers allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="letterAndNumberValidation()" value='Submit' />
</form>
</body>
</html>
IP Address Validation in JavaScript
We can validate IP Address using JavaScript easily.
<html>
<body>
<script type='text/javascript'>
function ipAddressValidation()
{
var ipAddressPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(document.getElementById('txtletter').value.match(ipAddressPattern))
{
alert("Yes you enter corrent IP address.");
return true;
}
else
{
alert('IP Address Validation Failed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="ipAddressValidation()" value='Submit' />
</form>
</body>
</html>
Example-5: Retrieve Today’s Date in JavaScript
We can retrive current date, current month, current year, curren time from Date using JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>getDate() method is used for display today's date in JavaScript</p>
<p id="currentDateDate"></p>
<p id="currentMonth"></p>
<p id="currentYear"></p>
<p id="currentFullDate"></p>
<p id="currentTime"></p>
<script>
var date = new Date();
document.getElementById("currentDateDate").innerHTML ="Current Date using JavaScript: "+date.getDate();
document.getElementById("currentMonth").innerHTML ="Current Month using JavaScript: "+(date.getMonth()+1);
document.getElementById("currentYear").innerHTML ="Current Year using JavaScript: "+date.getFullYear();
document.getElementById("currentFullDate").innerHTML ="Current Full Date using JavaScript: "+date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
document.getElementById("currentTime").innerHTML ="Current Time using JavaScript: "+date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
</script>
</body>
</html>
Once you run code, you can see the output like below:
Current Date using JavaScript: 23
Current Month using JavaScript: 9
Current Month using JavaScript: 2018
Current Full Date using JavaScript: 2018-9-23
Current Time using JavaScript: 20:58:59
Example-6: Reverse array javascript
We use arrays in JavaScript to store multiple values. We can easily reverse an array using JavaScript by using reverse() method.
We can able to see how the code is helpful to change the sequence of season.
Example-7: JavaScript concate or merge two Arrays
Now we will see how we can concate or merge two arrays in JavaScript by using the concat() method.
Here I have two arrays like:
var twoDay= ["Sunday", "Monday"];
var fiveDay= ["Tuesday", "Wednsday","Thursday", "Friday","Saturday"];
Below is the JavaScript code which will concat both the arrays.
<!DOCTYPE html>
<html>
<body>
<p>We will see after clicking the button how two array will join</p>
<button onclick="concateTwoArray()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
function concateTwoArray() {
var twoDay= ["Sunday", "Monday"];
var fiveDay= ["Tuesday", "Wednsday","Thursday", "Friday","Saturday"];
var totalDay = twoDay.concat(fiveDay);
document.getElementById("pId").innerHTML = totalDay ;
}
</script>
</body>
</html>
Example-8: Reverse String in JavaScript
We can reverse a string in JavaScript by using below script.
<!DOCTYPE html>
<html>
<body>
<p>Reverse String in JavaScript</p>
Main String: "Bijay Kumar";
<p id="reverseText"></p>
<script>
var reverseString=reverseStringMethod("Bijay Kumar");
document.getElementById("reverseText").innerHTML = "Reverse String: "+reverseString ;
function reverseStringMethod(str) {
var result = "";
for (var i = str.length - 1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
</script>
</body>
</html>
The result will appear like below:
Example-9: JavaScript Open a page using window.open() method
We can open a new web page using window.open() method in JavaScript. The below code will open https://www.tsinfotechnologies.com in a new window.
<!DOCTYPE html>
<html>
<body>
<p>In this example we can able to see how the winow.open method is used to open a new window page in JavaScript </p>
<button onclick="openNewWindow()" id="btnClick">Click</button>
<script>
function openNewWindow() {
window.open("https://www.tsinfotechnologies.com/");
}
</script>
</body>
</html>
Example-10: if else statement in JavaScript
We can use if/else statement to executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
<!DOCTYPE html>
<html>
<body>
<p>In this code we will check particular year is a leap year or not</p>
<script type="text/javascript">
var daysInFebruary=29;
if( daysInFebruary==29 ){
document.write("This year is a leapYear");
}
else
{
document.write("This is not a leapyear");
}
</script>
</body>
</html>
Example-11: Print page In JavaScript
We can print a page using window.print() method in JavaScript. Here once the user clicks on the button, Print setup page will appear.
<!DOCTYPE html>
<html>
<body>
<p><b>Here we will check how print method is work while clicking on button click<b></p>
<button onclick="PrintPage()" id="btnClick">Click it</button>
<script>
function PrintPage() {
window.print();
}
</script>
</body>
</html>
Example-12: Insert element in array javascript
This JavaScript example, we will see how we can insert an element into an array in JavaScript. We can use the Push method to insert an element to an array in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>In this code we will see how to push an element to array</p>
<button onclick="pushElementToArray()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
var days = ["Sunday", "Monday", "Tuesday", "Wednsday"];
document.getElementById("pId").innerHTML = days;
function pushElementToArray() {
days.push("Saturday");
document.getElementById("pId").innerHTML = days;
}
</script>
</body>
</html>
Example-13: get current url javascript
We can get currrent url using JavaScript by using the window.location.href attribute easily. You can see in the below JavaScript examples it display’s the current URL.
<!DOCTYPE html>
<html>
<body>
<p>This widow.location() method will display currently which page you are opening.</p>
<p id="pId"></p>
<script>
document.getElementById("pId").innerHTML ="The full URL of this page is:<br>" + window.location.href;
</script>
</body>
</html>
Example-14: getElementsByClassName() method in JavaScript
This example we will see how we can use getElementsByClassName() method in JavaScript. In an alert box, we are displaying the value from a class div.
<!DOCTYPE html>
<html>
<body>
<div class="myclass">The value is presented inside the class</div>
<button onclick="RetriveByClassName()" id="btnClick">Click</button>
<script>
function RetriveByClassName() {
var x = document.getElementsByClassName("myclass");
alert(x[0].innerHTML);
}
</script>
</body>
</html>
Example-15: getElementByName() method in JavaScript
We can use getElementByName() method to retrieve HTML element uisng name attribute. Here I am trying to check a checkbox based on the name attribute which we retrieve getElementByName() method.
<!DOCTYPE html>
<html>
<body>
<p>How to check a checkbox using getElementByName() method in JavaScript</p>
Tiger: <input name="forestAnimal" type="checkbox" value="Tiger">
Cow: <input name="domesticAnimal" type="checkbox" value="Cow">
<button onclick="retriveElementByName()" id="btnClick">Click</button>
<script>
function retriveElementByName(){
var animalName = document.getElementsByName("domesticAnimal");
var i;
for (i = 0; i < animalName.length; i++) {
if (animalName[i].type == "checkbox") {
animalName[i].checked = true;
}
}
}
</script>
</body>
</html>
Example-16: Disable Browser back and forward button in browser using JavaScript
By using JavaScript, we can easily disable browser back and forward button. We can use window.history.back() and window.history.forward() methods to disable browser back and forward button respectively.
Disable back button in browser using javascript
By using window.history.back() JavaScript method, we can disable browser back button in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Disable browser back button using JavaScript</p>
<button onclick="disableBackButton()" id="btnBack">Back</button>
<script>
function disableBackButton() {
window.history.back();
}
</script>
</body>
</html>
Disable Forward button in browser using JavaScript:
By using window.history.forward() we will be able to disable forward button in browser using JavaScript.
Example-17: Disable and Enable Dropdown List using JavaScript
We can easily enable or disable dropdown list using JavaScript by using disabled property.
Disable Dropdown list using JavaScript
Below is the JavaScript code which we can use to disable dropdown list.
<!DOCTYPE html>
<html>
<body>
<form>
<select id="selectAnimal">
<option>Cats</option>
<option>Dogs</option>
</select>
</form>
<p>Click the button to disable the dropdown list.</p>
<button onclick="disableDropDown()" id="btnClick>Click</button>
<script>
function disableDropDown() {
document.getElementById("selectAnimal").disabled = true;
}
</script>
</body>
</html>
Enable Dropdown list using JavaScript
Below is the JavaScript code which we can use to enable dropdown list. We can enable dropdown list by simply setting disabled property to false.
<!DOCTYPE html>
<html>
<body>
<form>
<select id="selectAnimal">
<option>Cats</option>
<option>Dogs</option>
</select>
</form>
<p>Click the button to enable the dropdown list.</p>
<button onclick="enableDropDown()" id="btnClick>Click</button>
<script>
function enableDropDown() {
document.getElementById("selectAnimal").disabled = false;
}
</script>
</body>
</html>
Example-18: Disable mouse right click using javascript
Below is the PowerShell script, by using which we can disable mouse right click using JavaScript.
<html>
<body >
<p>In this Example we can able to see how to disable mouse right click in JavaScript.</p>
<script type=”text/javascript”>
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = function() {
return false;
};
}
else {
document.onmouseup = function(x) {
if (x != null && x.type == “mouseup”) {
if (x.which == 2 || x.which == 3) {
return false;
}
}
};
}
document.oncontextmenu = function() {
return false;
};
</script>
Example-19: JavaScript Date Countdown Timer
We can display a javascript date countdown timer using javascript easily. Below is a timer example in JavaScript.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p id="pId"></p>
<script>
var expiredDate = new Date("Jan 5, 2020 15:37:29").getTime();
var t = setInterval(function() {
var nowdate = new Date().getTime();
var timePeriod = expiredDate - nowdate;
var days = Math.floor(timePeriod/ (1000 * 60 * 60 * 24));
var hours = Math.floor((timePeriod % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timePeriod % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timePeriod % (1000 * 60)) / 1000);
document.getElementById("pId").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (timePeriod < 0)
{
clearInterval(t);
document.getElementById("pId").innerHTML = "EXPIRED";
}
},
1000);
</script>
</body>
</html>
Once you run the code you can see the results like below:
Example-20: Check box validation using JavaScript (javascript checkbox checked)
This example shows how to check checkbox is checked or not in javascript. For this example, on a button click we are displaying if a check box is checked or not.
<!DOCTYPE html>
<html>
<body>
Checkbox: <input type="checkbox" id="chkBox">
<p>JavaScript check box validation example</p>
<button onclick="showCheckBoxAlert()" id="btnClick">Click</button>
<script>
function showCheckBoxAlert() {
var x = document.getElementById("chkBox");
if(!x.checked)
{
alert('Check box is unchecked');
return false;
}
else
{
alert('Check box is checked');
return false;
}
}
</script>
</body>
</html>
If user does not check the check box, it will display an alert message.
Example-21: get query string value in javascript
By using JavaScript we can retrieve query string values from a URL. Or we can get url parameter value by name using javascript.
In the output we can able to see: “WSSWebPartPage”
<html>
<body>
<button onclick="GetParameterValues('MyID')" id="btnClick">Click me</button>
<script>
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&");
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split("=");
if (urlparam[0] == param) {
return urlparam[1];
}
}
alert(urlparam[1]);
}
</script>
</body>
</html>
Example-22: JavaScript get or set radio button value
We can get radio button value easily using JavaScript.
Get radio button selected value using JavaScript
We can easily Get radio button selected value using JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Retrieve Get radio button selected value using JavaScript</p>
<p>Select the gender:</p>
<input type="radio" name="Gender" onclick="myFunction(this)" value="Male">Male<br>
<input type="radio" name="Gender" onclick="myFunction(this)" value="Female">Female<br>
<script>
function myFunction(Gender) {
alert(Gender.value);
}
</script>
</body>
</html>
Set radio button value using JavaScript
We can set radio button value using JavaScript by using JavaScript code.
<!DOCTYPE html>
<html>
<body>
<p>Set radio button value using JavaScript</p>
Married: <input type="radio" id="radiomarried">
Unmarried: <input type="radio" id="radioUnmarried">
<p>Click the "Try it" button to check the radio button.</p>
<button onclick="selectTheMariedButton()">Click if you are maried</button>
<button onclick="selectTheUnmariedButton()">Click if you are not maried</button>
<script>
function selectTheMariedButton() {
var x = document.getElementById("radiomarried");
x.checked = true;
alert("Married is selected");
}
function selectTheUnmariedButton() {
var y = document.getElementById("radioUnmarried");
y.checked = true;
alert("Unmarried is selected");
}
</script>
</body>
</html>
Example-23: JavaScript screen height
We can easily get screen height using JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example</p>
<p>When clicking on button it is showing the Screen height</p>
<button onclick="showScreenHeight()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
function showScreenHeight() {
var totalHeight = "Total Height: " + screen.height + "px";
document.getElementById("pId").innerHTML =totalHeight;
}
</script>
</body>
</html>
Example-24: auto refresh page javascript
Now we can see how we can auto refresh page using JavaScript.
Example-25: Convert Celcius Value to Faranheit Value in JavaScript
We see how we can convert celcius value to farahheit value in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Examples: Convert celcius to faranheit value</p>
<p>Celcius Value:<input id="txtCelcius" onkeyup="convert('C')"> </p>
<p>Farenhit Value:<input id="txtFahrenhit" onkeyup="convert('F')"> </p>
<script>
function convert(degree) {
var p;
if (degree == "C") {
p = document.getElementById("txtCelcius").value * 9 / 5 + 32;
document.getElementById("txtFahrenhit").value = Math.round(p);
} else {
p = (document.getElementById("txtFahrenhit").value -32) * 5 / 9;
document.getElementById("txtCelcius").value = Math.round(p);
}
}
</script>
</body>
</html>
Example-26: javascript get today’s date
We can retrieve today’s date using JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example:Showing Todays date and time</p>
<p>Todays date is:</p>
<p id="pId"></p>
<script>
var date = new Date();
document.getElementById("pId").innerHTML = date;
</script>
</body>
</html>
Example-27: Scroll Down Event in JavaScript
This JavaScript examples shows how can we use scroll down event in JavaScript.
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>This example is showing how scroll down event will work</p>
<div onscroll="scrollDownEvent()">TSInfo Technologies, one of the leading SharePoint Offshore SharePoint development company based out in Bangalore, India. We focus on SharePoint development, migration, support and training. May be it is web part development, workflow development or Add-in development, our SharePoint expert team will help you to deliver the project successfully. Our team has done few migration projects successfully, be it from MOSS 2007 -> SharePoint 2010 -> SharePoint 2013 -> SharePoint 2013, or migrating from SharePoint On-premises to SharePoint Online Office 365, we can deliver it succesfully. Are you looking out for an IT outsourcing partner?</div>
<p>Scrolled <span id="pSpan">0</span> times.</p>
<script>
var x = 0;
function scrollDownEvent() {
document.getElementById("pSpan").innerHTML = x += 1;
}
</script>
</body>
</html>
Example-28: JavaScript Animation example
Below is an example of JavaScript animation.
<!DOCTYPE html>
<html>
<style>
#myBigContainer {
width: 600px;
height: 500px;
position: relative;
background: pink;
}
#mySmallContainer {
width: 100px;
height: 50px;
position: absolute;
background-color: black;
}
</style>
<body>
<p>
<button onclick=" javaScriptAniminationForMove()">Try this</button>
</p>
<div id ="myBigContainer">
<div id ="mySmallContainer"></div>
</div>
<script>
function javaScriptAniminationForMove() {
var element = document.getElementById("mySmallContainer");
var p = 0;
var idValue = setInterval(frame, 30);
function frame() {
if (p == 500) {
clearInterval(idValue);
}
else
{
p++;
element.style.top = p+ 'px';
element.style.left = p + 'px';
}
}
}
</script>
</body>
</html>
Example-29: Play and Pause video in JavaScript
We can easly play video and pause video file in javascript.
<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example:Play and stop a video using JavaScript</p>
<p>When we click on Play button the video will play and when click on stop button the video will stop</p>
<button onclick="playVideo()" id="btnPlay()" type="button">Play The Video</button>
<button onclick="stopVideo()"id="btnStop" type="button">Stop The Video</button><br>
<video id="waterFallVid" width="320" height="250">
<source src="https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/WaterFall.mov" type="video/mp4">
</video>
<script>
var video = document.getElementById("waterFallVid");
function playVideo()
{
video.play();
}
function stopVideo()
{
video.pause();
}
</script>
</body>
</html>
You can see below example, by clicking on a button video is playing and in another button click video we are pausing the video using JavaScript.
Example-30: Change background color of div javascript
Below JavaScipt we can change background color of div like below:
<!DOCTYPE html>
<html>
<head>
<style>
#divId{
width: 300px;
height: 300px;
background-color:blue;
color: white;
}
</style>
</head>
<body>
<p>When Click on Button click the background colour will change.</p>
<button onclick="changeBackgroundColour()" id="btnClick">Click it</button>
<div id="divId">
Top 51 JavaScript examples.
</div>
<script>
function changeBackgroundColour() {
document.getElementById("divId").style.backgroundColor = "red";
}
</script>
</body>
</html>
Example-31: Change the page colour in Every 5 sec in JavaScript
We can easily change page color in regular intervals ( every 5 second ) in JavaScript.
<p>In this example we can able to see in every 5 second the page colour is changing using JavaScript</p>
<style>
#fullScreenId {
position: relative;
height: 100%;
width: 100%;
}
</style>
<body>
<div id="fullScreenId"></div>
<script>
var div = document.getElementById("fullScreenId");
function getRandomColorInEach5Sec() {
var letters = '0123456789ABCDEF';
var randomColor = '#';
for (var i = 0; i < 6; i++ ) {
randomColor += letters[Math.floor(Math.random() * 16)];
}
return randomColor;
}
function chnageTheFullScreenColour(){
div.style.backgroundColor= getRandomColorInEach5Sec();
}
setInterval(chnageTheFullScreenColour,1000);
</script>
</body>
</head>
</html>
Example-32: Display Message every 3 second using Javascript
By using JavaScript we can display message in regular intervals using JavaScript like below:
<!DOCTYPE html>
<html>
<body>
<p>After Click on button after 3 second we can able to see the text</p>
<button onclick="setTimeout(displayTextIn3SecondAfterClickOnButton, 3000);">Click On It</button>
<p id="pId"></p>
<script>
function displayTextIn3SecondAfterClickOnButton() {
document.getElementById("pId").innerHTML = document.write("Enjoy Top 51 JavaScript Example");
}
</script>
</body>
</html>
Example-33: JavaScript get max value in array of objects
In JavaScript, we can easily get max number in an array of objects. Below is the code which will give the max number in the array.
<!DOCTYPE html>
<html>
<body>
<p>By using Math.max.apply method we can find out the maximum array value</p>
<p>The maximum aray value is:</p>
<p id="pId"></p>
<script>
var marks = [40, 95, 70, 45, 75, 55];
document.getElementById("pId").innerHTML = maximumArayValue(marks);
function maximumArayValue(array) {
return Math.max.apply(null, array);
}
</script>
</body>
</html>
Example-34: Sort and Reverse an array of Objects using JavaScript
Below JavaScript examples, it shows how to sort and reverse an array of objects in JavaScript by using the sort() and reverse() method.
<!DOCTYPE html>
<html>
<body>
<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order.</p>
<button onclick=”sortAndReverseArrayValue()”>Click</button>
<p id=”pId”></p>
<script>
var banksOfIndis = [“CentralBankOfIndia”,”AndhraBank”,”BankOfBaroda”,”CanaraBank”,”AllhabadBank”];
document.getElementById(“pId”).innerHTML = banksOfIndis;
function sortAndReverseArrayValue() {
banksOfIndis.sort();
banksOfIndis.reverse();
document.getElementById(“pId”).innerHTML = banksOfIndis;
}
</script>
</body>
</html>
Example-35: Find index of Largest value in An Array in JavaScript
This JavaScript example explains how to find index of largest value in an array in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>In this example we can able to check the index value of largest array value</p>
<script>
var marks = [30, 100, 50, 90, 40];
function IndexValueOfALargestArrayValue(array){
var startingValue = 1;
var maximumValue = 0;
for(startingValue; startingValue < array.length; startingValue++){
if(array[maximumValue] < array[startingValue]){
maximumValue = startingValue;
}
}
return maximumValue;
}
document.write("The largest Number Index value is:" +IndexValueOfALargestArrayValue(marks));
</script>
</body>
</html>
Example-36: Try and Catch in JavaScript
This JavaScript example explains how to use try and catch in JavaScript. Try catch block is necessary for catching errors in JavaScript code.
<html>
<body>
<p id="pId"></p>
<script>
var x;
try {
x = y + 1;
document.write(x);
}
catch(err) {
document.write(err);
}
</script>
</body>
</html>
Example-37: Return Boolean value of an Integer In JavaScript
This JavaScript example shows how we can return boolean value of an integer express in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Click on the buton to check the boolean value of 100/10<p>
<button onclick="boleanValueOfANumber()" id="btnClick">Click</button>
<script>
function boleanValueOfANumber()
{
var x = 100;
var y=10;
var booleanValue=Boolean(100/10);
document.write(booleanValue);
}
</script>
</body>
</html>
We can able to see in the output is “true”.
Example-38: JavaScript Check an object is an array or not
We can check an object is an array or not in JavaScript by using the isArray() method. The isArray() method output will display true or false value.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to check if "fruits" is an array.</p>
<button onclick="checkArrayValueOrNot()" id="btnClick">Click </button>
<p id="demo"></p>
<script>
function checkArrayValueOrNot() {
var states =["Maharashtra","Tamil Nadu","Uttar Pradesh","West Bengal","Delhi"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(states);
}
</script>
</body>
Example-39: Print Stars in Pyramid Structure Using JavaScript
The javascript example explains how to print stars in pyramid structure in javascript.
<html>
<head>
<p>51 Top JavaScript Example: Print start in PyramidStructure using JavaScript</p>
<body>
<button onclick="printStarInPyramidStructure()" id="btnClick">Click me</button>
<script>
function printStarInPyramidStructure()
{
var rows=5;
for(var i=1;i<=rows;i++)
{
for(var j=1;j<=i;j++)
{
document.write(" * ");
}
document.write("<br/>");
}
}
</script>
</body>
</head>
</html>
We can display tooltip messages on mouse over in JavaScript. Below is the JavaScript code which will display tooltip message in JavaScript.
<html>
<head>
<style>
.name{
float:center;
margin:100px;
border:0.5px solid black;
}
.tooltip{
position:fixed;
margin:5px;
width:200px;
height:50px;
border:1px solid black;
display:none;
}
</style>
</head>
<body>
<div class = "name" onmouseover="show(tooltipFirstName)" onmouseout="hide(tooltipFirstName)">
FirstName:
<div class = "tooltip" id= "tooltipFirstName">
Give a Valid Name
</div>
</div>
<div class = "name" onmouseover="show(tooltipQualification)" onmouseout="hide(tooltipQualification)">
Qualification:
<div class = "tooltip" id= "tooltipQualification">
Enter your Qualification
</div>
</div>
<div class = "name" onmouseover="show(tooltipAdress)" onmouseout="hide(tooltipAdress)">
Permanenet Adress:
<div class = "tooltip" id= "tooltipAdress">
Give Your proper Permanenet address
</div>
</div>
<script>
function show (element) {
element.style.display="block";
}
function hide (element) {
element.style.display="";
}
</script>
</body>
Example-42: Reload page JavaScript
Reload is nothing but a method is used to reload the curent document. Below is the JavaScript code which will reload a page on button click. Once you click on the button, it will reload the page.
<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Example</p>
<p>This code is reload the page again</p>
<button onclick="ReloadThepage()" id="btnClick">Click Here To Reload The Page</button>
<script>
function ReloadThepage() {
location.reload();
}
</script>
</body>
</html>
Example-43: Break and Continue in JavaScript
This javascript exampl, you will see how to use break and continue in JavaScript.
JavaScript Break
This javascript example explains how to use break keyword.
This javascript example explains how to use conditional operator. This particular example user will enter his or her age and by using conditional operation it will check if the user’s age more than 18 years or not. If user’s age is greater than 18 years then we will show an alert message that “Eligibel for blood donation” else “Not eligibel for blod donation”.
<!DOCTYPE html>
<html>
<body>
<p>This example will display eligible for blod donation or not, Enter age in the text box</p>
<input id="txtage" />
<button onclick="exampleOfTernaryOpearator()" id="btnClick">Submit</button>
<p id="pId"></p>
<script>
function exampleOfTernaryOpearator() {
var minimumAge, donateable;
minimumAge = Number(document.getElementById("txtage").value);
if (isNaN(minimumAge)) {
donateable = "Input should be an integer value";
} else {
donateable= (minimumAge >18) ? "Eligibel for blood donation" : "Not eligibel for blod donation";
}
document.getElementById("pId").innerHTML =donateable;
}
</script>
</body>
</html>
Example-45: Example of this KeyWord in JavaScript
This javascript example shows how we can use this keyword inside javascript functions.
<!DOCTYPE html>
<html>
<body>
<p id="pId"></p>
<script>
// Create an object:
var MobilePhone= {
brandName: "Samsung",
modelNumber: 35566,
size:6,
fullName : function() {
return this.brandName +" "+"mobilephone"+ " " +"model number"+" "+ this.modelNumber;
}
};
// Display data from the object:
document.getElementById("pId").innerHTML = MobilePhone.fullName();
</script>
</body>
</html>
Example-46: JavaScript Validation API
This javascript example explains how we can use JavaScript validations API.
<!DOCTYPE html>
<html>
<body>
<p>51 JavaScript Examples: Form Validation</p>
<p>Price of SharePoint Book:</p>
<input id="txtNumber" type="number" min="200" max="500" required>
<button onclick="formValidation()" id="btnClick">Click</button>
<p>Price of SharePoint book must be in between 200 to 500</p>
<p id="pId"></p>
<script>
function formValidation() {
var inputValue = document.getElementById("txtNumber");
if (!inputValue.checkValidity()) {
document.getElementById("pId").innerHTML = inputValue.validationMessage;
}
else
{
document.getElementById("pId").innerHTML = "Input is valid";
}
}
</script>
</body>
</html>
Example-47: JavaScript Set dropdown value on Button Click
This JavaScript example explains how we can set dropdown value on button click. Here I have a dropdown list which has some values and on one button click I will set a particular value using JavaScript.
Example-48: Display Images Based on User Selection
This javascript example explains, how to display images based on user selection using JavaScript. Here I have uploaded two images and asked users to enter a number (1-2). Based on user’s selection it will display the image.
<html>
<head>
<body>
<p>Top 51 JavaScript Example:Pick a number and as per the number automatically image is displaying</p>
<img name="wave" src="https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/Wavepic.jpg" width="260" height="250" >
<script language="JavaScript">
var waveImage=new Array("https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/leavespic.jpg", "https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/waterfallFromTop.jpg");
var n = prompt("Pick a number 1 or 2");
n--;
document.images["wave"].src = waveImage[n];
</script>
</body>
</html>
Example-49: JavaScript Bind Arrays Value into Dropdown list
This javascript examples explain how to bind a dropdown list from an array in JavaScript. Here I have a country array whose values we are binding into a dropdownlist.
<html >
<head>
<p>51 Top JavaScript Example: Bind dropdown list from an array</p>
</head>
<body>
<input type="button" id="btnCountry" value="Populate the country name" onclick="populateCountryList()" />
<select id="ddlCountry">
</select>
<script type="text/javascript">
function populateCountryList() {
var country = [
{ Name: "India" },
{Name: "China" },
{ Name: "USA" },
{ Name: "Australia" }
];
var ddlCountry = document.getElementById("ddlCountry");
for (var i = 0; i < country.length; i++) {
var option = document.createElement("OPTION");
option.innerHTML = country[i].Name;
ddlCountry.options.add(option);
}
}
</script>
Example-50: javascript browser detection
This javascript example explains how to detect browser name in javascript. On a button click we are checking here which browser user is using, in javascript.
Example-51: How to sort array value using sort() method in JavaScript
We can easily sort array javascript, below is the code to sort an array values using JavaScript sort() method.
<!DOCTYPE html>
<html>
<body>
<p>sort array value in alphabatical order</p>
<p>Click on button click we can see our short array value</p>
<button onclick="banksNameInAlphabaticalOrder()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
var banksOfIndis = ["CentralBankOfIndia","AndhraBank","BankOfBaroda","CanaraBank","AllhabadBank"];
function banksNameInAlphabaticalOrder() {
banksOfIndis.sort();
document.getElementById("pId").innerHTML = banksOfIndis;
}
</script>
</body>
</html>
The above code will sort an array of objects in alphabetical order.
After working for more than 15 years in Microsoft technologies like SharePoint, Office 365, and Power Platform (Power Apps, Power Automate, and Power BI), I thought will share my SharePoint expertise knowledge with the world. Our audiences are from the United States, Canada, the United Kingdom, Australia, New Zealand, etc. For my expertise knowledge and SharePoint tutorials, Microsoft has been awarded a Microsoft SharePoint MVP (9 times). I have also worked in companies like HP, TCS, KPIT, etc.
Bijay thanks for the tutorial look forward to reviewing it.
Bijay thanks for the tutorial look forward to reviewing it.
Nice
Thank you sir for easy information provided.