create photo gallery with controlled time interval by user - javascript

I have read that lesson:
http://html.net/tutorials/javascript/lesson17.php
which contains an example:
http://html.net/tutorials/javascript/lesson17_ex1.html
but I need to create a photo gallery with possibility to choose time between photos by user, so I want to modified that line of code:
galleryStarter = setTimeout("startGallery()", 2000);
to be as user want, so I add:
<input type="text" name="name" id="name"><br>
<input type="button" id="btnSub" value="User gallery"/>
<input type="button" id="btnSub" value="User gallery"/>
also:
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var btnSub = document.getElementById("btnSub");
btnStart.onclick = startGallery;
btnStop.onclick = stopGallery;
btnSub.onclick = userGallery;
and:
function userGallery()
{
curImage.src = preloadedImgs[counter].src;
counter ++;
if (counter == preloadedImgs.length)
{
counter = 0;
}
var c=document.getElementById("name").value;
galleryStarter = setTimeout("userGallery()", c);
window.alert(c);
isGalleryOn = true;
}
but id didn't work.. what is the reason?

It is because you didn't clear previous timer.
clearTimeout(galleryStarter);
isGalleryOn = false;
Inside function userGallery() will solved your issue.
Check Fiddle Here.

Related

How to clone or create a nested DOM node and change all its containing id values according to a current id?

I need to display some numbers, strings from a class named Student, but i can't figure it out how i can change the id from children element. I have to use JavaScript.
what i tried to do:
class Student{
static count = 0;
constructor(nume, prenume, data_nasterii, foaie_matricola){
this.IdClasa = ++Student.count;
//definirea atributelor
this.nume = nume;
this.prenume = prenume;
this.data_nasterii = data_nasterii;
this.foaie_matricola = foaie_matricola;
}
afiseazaVarsta(){
}
afiseazaNotele(){
}
calculeazaMedia(){
}
adaugaNota(nota_noua){
}
}
var Stud = [new Student("Name", "Name1", "2000.01.01", "0123123"),
new Student("Green", "Blue", "2022/12.12", "321321")];
function afisareStudenti(){
let i = 0; let bol = false;
for(let x=1; x<=Student.count; x++) {
console.log(document.getElementById("AfisareStudenti"+x)==null);
if(document.getElementById("AfisareStudenti"+x)==null)
{
i = x;
bol = true;
break;
} else {
bol = false;
}
}
if((i<=Student.count)&&(bol==true)){
for(i; i<=Student.count; i++) {
console.log("i="+i);
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
console.log(divClone);
divClone.id = 'AfisareStudenti'+(i);
div.after(divClone);
var NumeStud = document.getElementById("NumeStudent"+(i-1));
var PrenumeStud = document.getElementById("PrenumeStudent"+(i-1));
var dataNastStud = document.getElementById("intData"+(i-1));
var FoaiaMatStud = document.getElementById("FoaiaMatStud"+(i-1));
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
}
}
}
and this is the html file(the div that i want to clone):
<!--AFISARE-->
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1"><br><br>
<input class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti()">
</form>
</div>
the class is saved in a dynamic array (could be n object of the class) so i have to make somehow to display the information dynamic. My version changes the id from all elements with the same id (every incrementation of i, the idnumber from id is incremented also). I tried to create that div with document.createElement but is impossible(at least for me) xD . I started coding in javascript 2 days ago, so please take it slow on me :(
I think i found the problem, but it doesn't solve it. (i need to put (i-1) when calling for getting the ids). (Newbie mistake)
Having commented ...
"I have the feeling that if provided with the broader picture the audience could be of much more help since the OP could be provided back with leaner/cleaner and better maintainable approaches."
... I nevertheless hereby lately provide a template-based approach which, besides supporting the OP's id based querying of student-items, is also easier to read and to maintain.
The code provided within the example-code's main function does not just implement the usage of the template-based node-creation via template literals and DOMParser.parseFromString but also prevents the default behavior of each student-form's submit-button by making use of event-delegation.
function createStudentElement(studentId) {
const markup =
`<div class="student-item" id="AfisareStudenti${ studentId }">
<h2> Afisare Student ${ studentId }</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent${ studentId }"><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent${ studentId }"><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData${ studentId }"><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud${ studentId }"><br><br>
<input
class="butoane" type="submit" value="Afisare"
onclick="afisareMeniuAfisStudenti(${ studentId })"
>
</form>
</div>`;
const doc = (new DOMParser).parseFromString(markup, 'text/html');
return doc.body.removeChild(doc.body.firstElementChild);
}
// the button click handler.
function afisareMeniuAfisStudenti(studentId) {
console.log({ studentId })
}
function main() {
const itemsRoot = document.querySelector('.student-items');
// - prevent any form-submit by making use of event-delegation.
itemsRoot.addEventListener('submit', evt => evt.preventDefault());
// - just for demonstration purpose ...
// ... create student-items from a list of student IDs.
[1, 2, 3, 4, 5].forEach(studentId =>
itemsRoot.appendChild(
createStudentElement(studentId)
)
);
}
main();
.as-console-wrapper { left: auto!important; width: 50%; min-height: 100%; }
<div class="student-items"></div>
Tom's answer above is what you want for the element id problem that you asked about.
For your code in particular, you are going to have a couple other problems:
Because the final input is type="submit", its going to reload the page by default when it is clicked. The name of the "onclick" function also needs to match the function you defined (afisareStudenti).
You have:
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()">
Change this to:
<input class="butoane" type="submit" value="Afisare" onclick="afisareStudenti(event)">
Now, when you click that button, it will call the afisareStudenti function and pass in the "event". So if you change:
function afisareStudenti(){
let i = 0; let bol = false;
to:
function afisareStudenti(event){
event.preventDefault()
let i = 0; let bol = false;
This will correctly call your function, and prevent the "default" action of that submit button from reloading the page.
To change the id attribute of children elements, you could use Element.querySelector() on divClone.
Because if you use Document.querySelector() or Document.getElementById() you will get the first element that matches your selector (i.e.children of div#AfisareStudenti1).
let i = 2;
var div = document.querySelector('#AfisareStudenti1');
var divClone = div.cloneNode(true);
divClone.id = 'AfisareStudenti'+(i);
divClone.querySelector("h2").innerText = "Afisare Student " + i;
var NumeStud = divClone.querySelector("#NumeStudent1");
var PrenumeStud = divClone.querySelector("#PrenumeStudent1");
var dataNastStud = divClone.querySelector("#intData1");
var FoaiaMatStud = divClone.querySelector("#FoaiaMatStud1");
NumeStud.id = "NumeStudent"+(i);
PrenumeStud.id = "PrenumeStud"+(i);
dataNastStud.id = "intData"+(i);
FoaiaMatStud.id = "FoaiaMatStud"+(i);
div.after(divClone);
<div id="AfisareStudenti1">
<h2> Afisare Student 1</h2>
<label>Ce student doriti sa modificati? </label>
<form>
<label>Nume:</label><br>
<input type="text" id="NumeStudent1" /><br>
<label>Prenume:</label><br>
<input type="text" id="PrenumeStudent1" /><br>
<label>Data Nasterii:</label><br>
<input type="date" id="intData1" /><br>
<label>Foaie matricola:</label><br>
<input type="text" id="FoaiaMatStud1" /><br><br>
<input class="butoane" type="submit" value="Afisare" onclick="afisareMeniuAfisStudenti()" />
</form>
</div>

How do I change the class of a forms parent if they enter it wrong?

I'm using a at the moment in order to add a search feature to my site. I want them to enter a number that starts with 765611 and then has 11 numbers after that; if they type in a correct number, it will run the below script:
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
If they enter a wrong number (i.e. one that does not start with 765611 and have 11 numbers proceeding it) the background of the div will flash red for two seconds (I assume the way this would be done is by adding a temporary class value which has a red background) with a transition as well, and the above code wouldn't run.
I'm pretty terrible (and new) to JS but looking at other peoples code and my basic knowledge, I assume it would have to be something along the lines of this:
var search = document.getElementByID('search');
a.addEventListener('submit',function(e) {
if document.getElementByID('searchbar').value = "765611[0-9]{11}$" {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
}
else {
**SET THE FORM'S CLASS TO "RED"?**
}
What is the best and most efficient way of doing this?
var a = document.getElementById('search');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
window.location.href = 'thecopperkings.co.uk'+b;
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
Please find the below answer.
working example can be found here jsFiddle
Add class red as .red { background-color:red !important;}
var a = document.getElementById('search');
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAppend) == -1)
{
document.getElementById(elementId).setAttribute("class", oldClass+ " "+classToAppend);
}
}
function removeClass(elementId, classToRemove){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToRemove) !== -1)
{ document.getElementById(elementId).setAttribute("class",oldClass.replace(classToRemove,''));
}
}
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('searchbar').value;
//regular expression to match your criteria and test the sample value
if(/^765611[0-9]{11}$/.test(b)) {
alert('success -> '+ b );
window.location.href = 'thecopperkings.co.uk'+b;
} else {
//append the class red for searchid which is in form element
appendClass('search','red');
//remove the red class after 2sec(2000milliseconds)
window.setTimeout(function(){removeClass('search','red');},2000);
}
});
<div>
<form class="search" id="search" method="get" action="html/player.html">
<input type="text" placeholder="What is your SteamID?" id="searchbar" name="id" maxlength="17">
<input type="submit" value="Search">
</form>
</div>
var patt = new RegExp("765611[0-9]{11}$");
var searchbar = document.getElementByID('searchbar');
var searchForm = document.getElementByID('search');
if( patt.test(searchbar.value) ){
searchForm.classlist.remove('error');
// do your magic
} else{
searchForm.classlist.add('error');
// And maybe an alert or notice for the user
}
Also, check out the html5 input attribute pattern=""

How to set placeholder value changeble

I Want placeholder value change by set interval but when i'm running my code nothing is happen.
Is there anyone who can help me.
<form>
<input type="text" placeholder="Enter E-mail" name="e-mail" id="email"/>
</form>
<script>
var holder = setInterval(function(){
var emailplaceholder = document.getElementById('email').placeholder;
if (emailplaceholder == 'Enter E-mail') {
document.getElementById('email').placeholder = 'yourmail#example.com';
document.getElementById('email').placeholder = emailplaceholder;
};
},400);
</script>
Here is a working plunkr: http://plnkr.co/edit/WFU7PGNYMcUKK180cCt7
Its possible your script was running before the dom was created or not running at all depending on when you loaded it
<input type="email" placeholder="abc#gmail.com" id="email" />
(function(){
var email = document.getElementById('email');
var interval = setInterval(function(){
email.placeholder = email.placeholder === 'abc#gmail.com' ?
'Enter email' : 'abc#gmail.com';
}, 1000);
function clearInterval(){
clearInterval(interval);
}
})();
I'm not entirely sure what the expected behaviour is, but your code is overriding the new placeholder value with the original placeholder value stored in the emailplaceholder variable.
If you want the 'yourmail#example.com' value just remove the last line of code in the setinterval function.
e.g
<script>
var holder = setInterval(function(){
var emailplaceholder = document.getElementById('email').placeholder;
if (emailplaceholder == 'Enter E-mail') {
document.getElementById('email').placeholder = 'yourmail#example.com';
// document.getElementById('email').placeholder = emailplaceholder;
};
},400);
</script>
This will set the placeholder to be: yourmail#example.com after 400ms.
If you want something else to happen, please update your post to indicate the expected functionality.

how to store input box number in jQuery

Imagine how a normal calculator do. Use click button to input the data in a display box. Now i want to click a button to show "+" and also remove all the number in display but store it. So I can click to show the new number. After that, store those data include number1, "+" and number 2. For example: ("1","+" "2"). The reason of doing that but not using javascript for normal calculating is because I want to use Ajax to send to php and use php to execute the maths.However, I get stuck in this part.
var memory = "";
$("#add").click(function() {
memory += $show.val() + "+";
if($show.val().length >= 1){
$show.val("+");
} else {
$show.val("");
}
}
[Obligatory warning against evaluated code from a string on a server]
I would recommend trying to get a working version of your project using only javascript before trying more advanced concepts.
var memory = [];
$("#add").click(function() {
var val = $show.val();
if (val)
memory.push(val);
$show.val('+');
});
$('#submit').click(function () {
var s = memory.join('+');
memory = [];
$.get(...
});
Check Fiddle here
var one = $("#one");
var two = $("#two");
var add = $("#add");
var show = $("#show");
var equal = $("#equal");
var memory = "";
one.click(function(){
memory += "1";
show.val("1");
});
two.click(function(){
memory += "2";
show.val("2");
});
add.click(function(){
memory += "+";
if(show.val().length >= 1)
show.val("+");
else
show.val("");
});
equal.click(function(){
show.val(memory)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="show" type="text"/>
<input id="one" type="button" value="1"/>
<input id="two" type="button" value="2"/>
<input id="add" type="button" value="+"/>
<input id="equal" type="button" value="="/>

Check if two elements have been clicked, and a value has been entered in a textbox in Javascript

Here's a demo of what I'm talking about - http://jsfiddle.net/MatthewKosloski/qLpT9/
I want to execute code if "Foo" has been clicked, and a number has been entered in the input.. and if "send" has been clicked.
<h1>Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="send">Send</button>
I'm pretty sure I'm overthinking this, I'd appreciate the help on such a concise question.
try this one: jfiddle link
var send = document.getElementById("send");
var h1 = document.getElementsByTagName("h1");
var foo_clicked = 0;
h1[0].onclick = function(){foo_clicked += 1; };
send.onclick = function(){
if(document.getElementById("amount").value !='' && foo_clicked >0 )
alert ('poor rating');
};
As per your statement & taking some assumptions, try this way:
(This executes function twice - When there is a change of text or a click of the button).
HTML:
<h1 id="">Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="sendBtn">send</button>
JS:
document.getElementById("amount").addEventListener("change",poorRatingCalculation);
document.getElementById("sendBtn").addEventListener("click",poorRatingCalculation);
function poorRatingCalculation() {
var rating = document.getElementById("amount").value;
if(rating=="poor") alert("Poor Service");
}
DEMO: http://jsfiddle.net/wTqEv/
A better, self contained example:
http://jsfiddle.net/qLpT9/7/
(function()
{
var clicked = false;
var header = document.getElementById("header");
var amount = document.getElementById("amount");
var send = document.getElementById("send");
header.addEventListener("click", function()
{
clicked = true;
});
send.addEventListener("click", function()
{
if(!clicked)
{
return
}
// Foo has been clicked
var value = amount.value;
console.log(value;)
});
})();
Is this what you were looking for?
http://jsfiddle.net/qLpT9/5/
function poorRatingCalculation(){
if(myInput.value) {
alert(myInput.value);
}
}
var foo = document.getElementById("foo"),
myInput = document.getElementById("amount");
foo.addEventListener("click", poorRatingCalculation, false)

Categories