javascript for loop function - javascript

I have this index.html
<html>
<head>
<script type="text/javascript" src="scripts.js" > </script>
</head>
<body>
<center><h1>Images</h1></center>
<center>
<img id="b1" onclick="image()" src="1.jpg">
<img id="b2" onclick="image()" src="2.jpg">
<img id="b3" onclick="image()" src="3.jpg">
<img id="b4" onclick="image()" src="4.jpg">
</center>
</body>
</html>
and this scripts.js
function image(){
for(var i = 1; i < document.images.length; i++)
{
document.write(i);
}
when i click the first image it just show the number 1 on screen and the browser get stuck thinking.
why is doesnt show 123?

The reason why your loop isn't working is because the first time you call
document.write
it's removing all of the images from the page, and thus, reducing the length of the document.images node list to zero.
If you want to see 1234, instead of using document.write (which is deprecated anyway as Dai pointed out) use:
document.body.innerHTML += i;
Also, as Dai correctly points out, the first array index is 0 not 1, so your for loop should be as follows:
for(var i = 0; i < document.images.length; i++)
{
document.body.innerHTML += i;
}
Notice: var i = 0;

Array indexes start at 0 in ECMAscript, not 1, you'll need to rewrite your loop as so:
for(var i=0;i<document.images.length;i++) {
}
Note that document.write is now considered bad-practice as it triggers a lot of heavy-lifting in the browser's DOM and layout engines. Instead use document.createElement.

Related

Block all inappropriate words in the textbox when click button

Below is my code which show me notice of inserting kill , fight, slap when i insert in the textbox.
But i want to block all inappropriate words possible in the textbox like f**k and so on. DO you guys have any ideas. Thanks
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="wrapper" style="width:600px; margin:0 auto;">
<h2></h2>
<input id="txtWords" style="width:300px;" />
<br />
<input type="button" id="btnCheck" onclick="fnCheckForRestrictedWords();" value="Check For
Restricted Words">
</div>
<script type="text/javascript">
function fnCheckForRestrictedWords() {
var restrictedWords = new Array("kill", "fight", "slap");
var txtInput = document.getElementById("txtWords").value;
var error = 0;
for (var i = 0; i < restrictedWords.length; i++) {
var val = restrictedWords[i];
if ((txtInput.toLowerCase()).indexOf(val.toString()) > -1) {
error = error + 1;
}
}
if (error > 0) {
alert('You have entered some restricted words.')
}
else {
// Your logic here
}
}
</script>
</body>
</html>
You need to define all "bad" words and put them in your blacklist. You can use some existing lists as a starting point for your list:
https://github.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/blob/master/en
https://github.com/dariusk/wordfilter/blob/master/lib/badwords.json
http://www.bannedwordlist.com/lists/swearWords.txt
http://www.frontgatemedia.com/new/wp-content/uploads/2014/03/Terms-to-Block.csv
Source: Reddit
If you want to include obfuscated "bad" words you may need to add the to the list as well.
The
includes()
method should work: txtInput.includes(restrictedWords[i]) which returns either true or false. You also want to include more bad words and different ways to write them

JQuery: Hide all images except one, starting from the first one and scrolling it

I can't change the HTML code, and it looks like this:
<div class="slider">
<div class="slider-control">
<button id="prev">Previous</button>
<button class="foll">Next</button>
</div>
<div class="slider-image">
<img src="html.png" alt="Html" />
<img src="css.png" alt="Css" />
<img src="jquery.png" alt="jQuery" />
</div>
</div>
When the program starts I need to show the first image. If I click on "Previous" I want to show the previous img (if the currently img showed is the first one, I want to show the last one), if I click on "Next" then I want to show the next img.
I need it to be a generic solution case I need to use it also with more images.
I tried with:
function showImage(){
$(".slider-image img").not(":eq(n)").hide();
}
$(document).ready(function(){
n = 0;
showImage(n);
$(".slider-control button").click(function(){
if($(this).is("div.slider-control.prev")){
n -= 1;
showImage(n);
}
else if($(this).is("div.slider-control.foll")){
n += 1;
showImage(n);
}
});
});
But it doesn't show anything
There was a few issues that I've fixed for you, but this should now work okay for you
showImage was not taking n as a paramater, but you were passing it that when you were calling it
function showImage() {... // Not taking the param you're passing
function showImage(n) {... // Now we are, and assigning it the name 'n'
You weren't using .show() on the element you wanted to show - you were only ever using .hide()
There was also an issue with how spamming the next or previous buttons would change the n higher / lower than your element count, and so you would end up selecting elements that didn't exist. To keep your n within the range of your elements, you can do this to loop back around an array's indexes
n = n % $('.slider-image img').length;
Finally, you weren't passing n to the :not(:eq(n)) - I've just used template literals to insert the variable cleanly
In the HTML, I set your buttons to both use IDs, because I felt this made more sense and helps readabilit
In the $(document).ready(..., you also had an error with your .is() - You were alredy working from the <button> element, so you're okay to check just on the ID of the buttons
function showImage(n){
n = n % $(".slider-image img").length;
$(".slider-image img").not(`:eq(${n})`).hide();
$(".slider-image img").eq(n).show();
}
$(document).ready(function(){
n = 0;
showImage(n);
$(".slider-control button").click(function(){
if($(this).is("#prev")){
n -= 1;
showImage(n);
}
else if($(this).is("#foll")){
n += 1;
showImage(n);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slider">
<div class="slider-control">
<button id="prev">Previous</button>
<button id="foll">Next</button>
</div>
<div class="slider-image">
<img src="https://via.placeholder.com/150" alt="Html" />
<img src="https://via.placeholder.com/200" alt="Css" />
<img src="https://via.placeholder.com/250" alt="jQuery" />
</div>
</div>

calling function inside script tag not working [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
i have created an automated slideshow which should change the picture after every 2 secs;
i call the function changeSlide() at first then it should recursively call itself using the function setTimeout. but this doesn't work when page is first started or the page is refreshed.
but when i click on the button it starts working.
let slideIndex = 0;
changeSlide();
function changeSlide(){
slideIndex++;
let images = document.getElementsByClassName('image');
for (let i = 0; i<images.length;i++){
images[i].style.display="none";
}
if (slideIndex>= images.length){
slideIndex = 0;
}
images[slideIndex].style.display = "block";
setTimeout(changeSlide,2000);
}
This is my html code.
<div class="w3-display-container w3-content">
<img class="image" src="city.jpg" style="width: 100%;height:500px;" >
<img class="image" src="profile.png" style="width: 100%; height:500px;display:none;" >
<img class="image" src="img_girl.jpg" style="width: 100%;height:500px; display:none;" >
</div>
<button onClick="changeSlide()">Click Me</button>
i want my slideshow to start as soon as i start my page.
instead of changeSlide(); do window.onload=changeSlide; that way you make sure the DOM exists when calling the function
You currently seem to not have any code that tells your page to run the function when it's loaded. Try adding the following to your body tag:
<body onload="changeSlide()">
<!-- your other HTML code here -->
</body>
You should call changeSlide when browser has parsed your HTML markup, so it can access HTML elements. You have some options to make this work correctly.
Place your JS code after your HTML markup (After the <div> element containing images). Or just call changeSlide after it:
<script>
let slideIndex = 0;
function changeSlide(){
...
}
</script>
<div class="w3-display-container w3-content">
...
</div>
<script>
changeSlide();
</script>
Run changeSlide after page load using DOMContentLoaded event:
window.addEventListener('DOMContentLoaded', function(event){
changeSlide();
});
// Or just:
window.addEventListener('DOMContentLoaded', changeSlide);

All buttons have same width - jQuery

Im programming a calculator and Im trying that all the buttons in the same column has the same width. For that Im using jQuery (Im doing it this way cause I have an exam in some days and I wanna practice).
My HTML code:
<html>
<head>
<meta charset="UTF-8">
<title>CORE2017 P3</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="calculadora.js"></script>
<link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
</head>
<body onload="igualarBotones()">
<header>
<p>Calculator</p>
</header>
<section id="main">
<p>
Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
</p>
<p>
<button id="suma" class="columna1">+</button>
<button id="resta" class="columna2">-</button>
<button id="cuadrado" class="columna3">x<sup>2</sup></button>
</p>
<p>
<button id="inverso" class="columna1">1/x</button>
<button id="raiz" class="columna2">sqrt(x)</button>
<button id="pentera" class="columna3">parte_entera(x)</button>
</p>
<p>
<button id="potencia2" class="columna1">2<sup>x</sup></button>
<button id="factorial" class="columna2">x!</button>
<button id="igual" class="columna3">=</button>
</p>
</section>
</body>
</html>
My JavaScript code:
$(function() {
function igualarBotones(){
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
}
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(columna[i].css("width") > maxColumna){
maxColumna = columna[i].css("width");
}
}
for(i=0; i<columna.length; i++){
columna[i].css("width",maxColumna);
}
}
});
Anyone knows why it isnt working?
EDIT: I used $(columna[i]).css instead of columna[i].css and it worked. However I dont achieve that my function igualarBotones() gets defined when loading the body, I think it must be something related to how I named or wrote the function. If I write the Javascript this way:
$(function() {
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
maxColumna = $(columna[i]).css("width");
}
}
columna.css("width",maxColumna);
}
});
it works, but I want to do it with a function igualarBotones() that gets loaded with the body. Any idea what am I doing wrong?
Thank you all, Luis.
The issue is understanding the different between jquery representation of elements and "raw" elements in javascript.
Given var columna1 = $(".columna1"); what this means is that it will return a jquery object that is a collection of all elements that the selector (.column1 in this case) has specified.
When you iterate through this jquery collection (columna[i]) you don't get a jquery representation of the elements but actually the raw elements themselves (or a native javascript representation of the elements). Native javascript elements do not have a .css function.
So when you wrap each element around $(...) by doing this $(columna[i])you are then once again dealing with a jquery representation of each element and as such you are able to use .css. That is why the former does not work and the later works.
EXTRA SUGGESTION
Since you are learning jquery let me add this: Jquery has a .each function that you should actually use to loop over a jquery object that contains elements.
So this function:
function setMax(columna){
var maxColumna = -1;
for(i=0; i<columna.length; i++){
if(parseFloat($(columna[i]).css("width")) > parseFloat(maxColumna)){
maxColumna = $(columna[i]).css("width");
}
}
columna.css("width",maxColumna);
}
Could/Should be:
function setMax(columna){
var maxColumna = -1;
columna.each(function(){
// note the use of "this" to represent each
// element currently being iterated over.
// this = raw element, $(this) = jquery object representing element.
if(parseFloat($(this).css("width")) > parseFloat(maxColumna)){
maxColumna = $(this).css("width");
}
});
columna.css("width",maxColumna);
}
LAST TIP
I personally assist/help myself remember jquery object in my javascript code by prepending $ to all variables that are jquery objects so as to not forget them.
So this:
var columna1 = $(".columna1");
Would be:
var $columna1 = $(".columna1");
I'm not familiar with a .css function in vanilla javascript. I changed that so it would call the jQuery .css function. Also, at least in the pen, the function wasn't defined when the body was loading. Something is still off in how you're finding the max size, but this should get you started.
function igualarBotones(){
var columna1 = $(".columna1");
setMax(columna1);
var columna2 = $(".columna2");
setMax(columna2);
var columna3 = $(".columna3");
setMax(columna3);
}
function setMax(columna){
var maxColumna = -1;
for(var i=0; i<columna.length; i++){
if($(columna[i]).css("width") > maxColumna){
maxColumna = $(columna[i]).css("width");
}
}
for(i=0; i<columna.length; i++){
$(columna[i]).css("width",maxColumna);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>CORE2017 P3</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="calculadora.js"></script>
<link href="calculadora.css" rel="stylesheet" type="text/css" media="all">
</head>
<body onload="igualarBotones();">
<header>
<p>Calculator</p>
</header>
<section id="main">
<p>
Número: <input type="text" id="pantalla"> <button id="Limpiar">Limpiar</button>
</p>
<p>
<button id="suma" class="columna1">+</button>
<button id="resta" class="columna2">-</button>
<button id="cuadrado" class="columna3">x<sup>2</sup></button>
</p>
<p>
<button id="inverso" class="columna1">1/x</button>
<button id="raiz" class="columna2">sqrt(x)</button>
<button id="pentera" class="columna3">parte_entera(x)</button>
</p>
<p>
<button id="potencia2" class="columna1">2<sup>x</sup></button>
<button id="factorial" class="columna2">x!</button>
<button id="igual" class="columna3">=</button>
</p>
</section>
</body>
</html>

inexplicable math error in javascript

I have a function, used to clone the flash article scroller this page. Unfortunately I'm behind a firewall so can't upload my own code, but that should give you an idea. The function:
function select(id) {
alert(active+"\n"+((active+1)%4));
var prev = active;
active = (typeof(id) == "undefined" ? (active+1)%4 : id);
$("#panel").animate({"top": tops[active]}, 750);
$("#main"+prev).fadeOut(750);
$("#main"+active).fadeIn(750);
}
So if select() is called without an id, it simply progresses to the next item in sequence, otherwise it goes to the selected item. It's run on a timer defined:
timer = setInterval("select()", 5000);
When an object is mouseovered, this function is run:
$("img.thumb").mouseover(function() {
clearInterval(timer);
select($(this).attr("id").substr(-1));
timer = setInterval("select()", 5000);
});
The trouble is that, after a mouseover, the select function fails for one cycle, with the next object having no relation to the previous. The chosen object is consistent - it remains the same with each refresh given the same initial conditions, but it's unrelated in any way I can determine.
What is oddest is that the alert I run at the start of select(), which should be a straightforward mathematical operation, fails, claiming that (for the sequence I test - wait for an automatic scroll from 0 - 1, then mouseover 3) (3+1)%4=3.
I've tested this in both firefox and chrome, so it seems to be inherent to javascript.
I can only assume that it's storing two different values for active somehow, but nature of that schism, and how to resolve it, are beyond me.
I've attached the entire file below in case anything else is pertinent. Seems unlikely, but at this point I'm not ruling anything out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta http-equiv="imagetoolbar" content="no" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//alter these as you please
var thumbs = ["images/1t.png", "images/2t.png",
"images/3t.png", "images/4t.png"];
var mains = ["images/1.png", "images/2.png",
"images/3.png", "images/4.png"];
var links = ["http://www.goldcoast.com.au/gold-coast-beaches.html",
"http://www.goldcoast.com.au/gold-coast-whale-watching.html",
"http://www.goldcoast.com.au/gold-coast-hinterland-rainforest.html",
"http://www.goldcoast.com.au/gold-coast-history.html"];
//don't touch these
var timer = null;
var active = 0;
var tops = [0, 77, 155, 234];
function select(id) {
alert(active+"\n"+((active+1)%4));
var prev = active;
active = (typeof(id) == "undefined" ? (active+1)%4 : id);
$("#panel").animate({"top": tops[active]}, 750);
$("#main"+prev).fadeOut(750);
$("#main"+active).fadeIn(750);
}
$(function() {
for(var i = 0; i < 4; i++) {
$("#thumb"+i).attr("src", thumbs[i]);
$("#main"+i).attr("src", mains[i]);
}
$("#main"+active).show();
$("img.thumb").mouseover(function() {
clearInterval(timer);
select($(this).attr("id").substr(-1));
timer = setInterval("select()", 5000);
});
timer = setInterval("select()", 5000);
});
</script>
<style type="text/css">
#container {position:relative;}
#panel {position:absolute;left:0px;top:0px;z-index:1;}
img.thumb {position:absolute;left:8px;z-index:2;}
#thumb0 {top:7px;}
#thumb1 {top:84px;}
#thumb2 {top:162px;}
#thumb3 {top:241px;}
img.main {position:absolute;left:118px;top:2px;display:none;}
</style>
</head>
<body>
<div id="container">
<img src="images/panel.png" id="panel" />
<img id="thumb0" class="thumb" />
<img id="thumb1" class="thumb" />
<img id="thumb2" class="thumb" />
<img id="thumb3" class="thumb" />
<img id="main0" class="main" />
<img id="main1" class="main" />
<img id="main2" class="main" />
<img id="main3" class="main" />
</div>
</body>
</html>
Use parseInt() as comment suggested.

Categories