I'm writing the first item of an array to the screen, and would like to create Next/Previous buttons for array, but I can't get it to work. I have tried several methods, but I can't find suitable solution.
Can anyone help?
This is the last one I have tried:
<div>
<script type="text/javascript">
sav = new Array(
"first item",
"second item",
"third item",
);
document.write(sav[0] + " <br>");
</script>
</div>
<div>
Previous
Next!
</div>
Say you have an Array var arr = ['foo', 'bar', 'baz'];.
If you want to dynamically choose items from this Array, you'll need a new variable. Let's call this i and give it a default value var i = 0;
So far, arr[i]; // "foo" (i === 0)
Next and Previous
Now, lets write a function to choose the next item by modifying i. We may want to consider what we want to happen when i is bigger than (or equal to) arr.length as well.
function nextItem() {
i = i + 1; // increase i by one
i = i % arr.length; // if we've gone too high, start from `0` again
return arr[i]; // give us back the item of where we are now
}
Next, lets do the reverse, this time we might want to consider what should happen for negative i
function prevItem() {
if (i === 0) { // i would become 0
i = arr.length; // so put it at the other end of the array
}
i = i - 1; // decrease by one
return arr[i]; // give us back the item of where we are now
}
So far,
nextItem(); // "bar" (i === 1)
prevItem(); // "foo" (i === 0 as we did `0 + 1 - 1`)
// also
prevItem(); // "baz" (decreased on 0)
nextItem(); // "foo" (increased at end of arr)
Great, so we've got the basic algorithms down.
Connecting this to the DOM
First thing to note is that document.write is nearly always a bad idea. Instead, why not give our Elements some unique id attributes and use DOM methods in JavaScript after the Elements exist.
<div id="output"></div>
<div>
<span id="prev_button">Previous</span>
<span id="next_button">Next!</span>
</div>
So now we can access the first <div> in JavaScript as document.getElementById('output'), and the two <span>s similarly.
Now, let's set the initial text in the <div>, this is quite easy
document.getElementById('output').textContent = arr[0]; // initial value
// if i is still at it's default value, we could have used i instead of 0
Next, we need to add event listeners to the <span>s so they perform an action. The handler of each will set the text of the <div> in a similar way to above, but using the relevant function from earlier.
document.getElementById('prev_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('output').textContent = prevItem();
}
);
document.getElementById('next_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('output').textContent = nextItem();
}
);
This is great! Now the only thing left to do is make sure it runs "after the Elements exist". There are two ways to do this, either by putting the <script> element after the elements it uses, or by listening for the load event on window, i.e.
window.addEventListener('load', function () {
// DOM related JavaScript goes here
});
DEMO of everything together
If you want to do this multiple times or are mixing it with other JavaScript, you may need to consider variable name conflicts. The easiest way to get around this is by using an IIFE to create a "safe place" for your variables, but this answer is already long enough.
Try this way easier and corrected.
<script type="text/javascript">
var text = [
"first item",
"second item",
"third item"
];
var Current = 0;
document.getElementById("textHere").innerHTML = text[Current];
function Prev(){
if(Current == 0){
Current = text.length - 1;}
else{
Current--;}
document.getElementById("textHere").innerHTML = text[Current];
}
function Next(){
if(Current == text.length - 1){
Current = 0}
else{
Current++;}
document.getElementById("textHere").innerHTML = text[Current];
}
</script>
<div id="textHere"></div>
<div>
<button onclick="Next();">Next!</button>
<button onclick="Prev();">Previous</button>
</div>
Try this way, easier and corrected. -Alfa College Application Developer.
<script type="text/javascript">
var text = [
"first item",
"second item",
"third item"
];
var Current = 0;
document.getElementById("textHere").innerHTML = text[Current];
function Prev(){
if(Current == 0){
Current = text.length - 1;}
else{
Current--;}
document.getElementById("textHere").innerHTML = text[Current];
}
function Next(){
if(Current == text.length - 1){
Current = 0}
else{
Current++;}
document.getElementById("textHere").innerHTML = text[Current];
}
</script>
<div id="textHere"></div>
<div>
<button onclick="Next();">Next!</button>
<button onclick="Prev();">Previous</button>
</div>
Related
I am writing a little clicking game with javascript at the moment and I am currently stuck with a little challenge. I need it so that whenever i have clicked a button 10 times. my second value should increase by one. Maybe a little bit hard to understand, I'll try to explain it in code.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
Amount = 0;
// Whenever I click the button..The Amount increases like this.
Amount++;
// so after one click the amount should be..
Amount = 1;
// I need it so that when the button has been clicked 10 times I want to display //that. Something like this.
timesThatTheButtonHasBeenClickedTenTimes = 1;
Should I do this with a while loop or what.
// Let's just say I have this variable.
var timesThatTheButtonHasBeenClickedTenTimes = 0;
// So let's say I have an amount of times clicked.
var amount = 0;
var counter = function () {
amount++;
if (amount === 10) {
amount = 0;
timesThatTheButtonHasBeenClickedTenTimes++;
}
document.getElementById('clicks').innerHTML = amount;
document.getElementById('hits').innerHTML = timesThatTheButtonHasBeenClickedTenTimes;
};
document.getElementById("mybutton").addEventListener("click", counter);
<button id='mybutton'>
Click me!
</button>
<p>
Clicks = <span id='clicks'>0</span>
</p>
<p>
10 times hits = <span id='hits'>0</span>
</p>
Hope it helps!
You could do something like:
var timesButtonClicked = 0;
var secondValue = 0;
if (timesButtonClicked === 10) {
secondValue++;
timesButtonClicked = 0;
} else {
timesButtonClicked++;
}
This is the very simple solution for you problem:
var clicks = 0;
Clicker = function() {
clicks++;
console.log('You clicked '+clicks+' times already.');
if(clicks == 10){
alert('Something what you want to alert.')
clicks = 0;
}
}
<button onclick="Clicker()">
Click me 10x times pls
</button>
One approach I'd suggest is:
function increment() {
// find the current number of times the <button> has been clicked,
// if the <button> has a data-current attribute we retrieve that
// attribute-value and parse it as a number in decimal format;
// if it does not have that custom data-* attribute we set the
// variable to 0:
let currentValue = this.dataset.current ? parseInt(this.dataset.current, 10) : 0;
// here we update the data-current attribute to the incremented value
// of the currentValue:
this.dataset.current = ++currentValue;
// we retrieve the element with the id of 'clicks', and set
// its textContent to the value held by the currentValue:
document.getElementById('clicks').textContent = currentValue;
// here we retrieve the element with an id of 'numberOfTens',
// and set its textContent to the floored value of the currentValue
// divided by 10:
document.getElementById('numberOfTens').textContent = Math.floor(currentValue / 10);
}
// here we retrieve the element with the id of 'clicker':
document.getElementById('clicker')
// and bind the increment() function (note the deliberate lack of
// parentheses) as the event-handler for the 'click' event:
.addEventListener('click', increment);
div:empty::before {
content: '0';
}
#clicks::after {
content: ' clicks.';
}
#numberOfTens::after {
content: ' tens of clicks.';
}
<button id="clicker">Click</button>
<div id="clicks"></div>
<div id="numberOfTens"></div>
References:
CSS:
:empty pseudo-class.
Pseudo-elements, ::before, ::after.
content property.
JavaScript:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.
parseInt.
Pre-increment variable ++variableName.
I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")
I'm currently in the process of making a website for my band, and one idea I had was that on a specific page, you would see a picture of each band member, and when you hover over it with your mouse the picture would change and you would hear that band member saying something, then when you click on them, they say something else and you'll be redirected to their page.
This alone isn't a problem, but for one member, I want it to take three clicks before you actually get redirected to his page; I also want him to say something different at each click.
So what I'm basically looking for is a way to create different events on the first, second and third click (preferably using javascript).
I hope you guys can help me out, thanks in advance!
Just use variable to count clicks:
var count = 0
$(".test").click(function() {
count++;
if(count == 1) {
$(".test").text("first");
}else if(count == 2){
$(".test").text("second");
}else if(count == 3){
$(".test").text("third");
count = 0;
}
})
http://jsfiddle.net/x83bf1gq/4/
An option could be to create an onclick handler that keeps saying things until all texts in an array of texts are said. Once all the texts have been said, you can just redirect or whatever action you need to be done. Example:
var johnTexts = [
'hello',
'how are you doing',
'come on'
];
var jamesTexts = [
'ready',
'go'
];
var sayTexts = function (texts) {
var i = 0;
return function () {
if (i < texts.length) {
alert(texts[i++]);
} else {
alert('do your redirect or whatever you need');
}
};
}
document.getElementById('john').onclick = sayTexts(johnTexts);
document.getElementById('james').onclick = sayTexts(jamesTexts);
See demo
Simply set an event listener that makes different actions based on a global counter of clicks.
Check this fragment of code:
//set counter
var counter = 0;
var component = document.getElementByID("ID-of-component");
component.addEventListener('mouseover', function(){
//do something
});
component.addEventListener('click', function() {
switch(++counter) {
case 1: /* do something */ break;
case 2: /* do something */ break;
case 3: /* do something */ break;
}
counter = 0; //reset counter
});
Obviously, you have to write this code for each component of your band.
My JavaScript code is:
<script type="text/javascript">
var current = 0;
var cars = new Array(5);
cars[0] = "Audi";
cars[1] = "Bentley";
cars[2] = "Mercedes";
cars[3] = "Mini";
cars[4] = "BMW";
document.getElementById("addCarBtn").onclick = function () {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
</script>
I want to display the value of each array item one by one on button click the div.
But when i click the button, the array[0] i.e "Audi" is displayed but just for fraction of seconds. then it disappears and only the button is visible.
You can use a loop like:-
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
//It will show alert 5 times. You'll need to click through ok to traverse all array elements.
//I think it is what you're thinking, or have I interpreted it wrong.
// I'm assuming you're completely new to javascript then on your button write onclick="yourFuncName();"
function YourfuncName()
{
//Initailze your array here, like you have done or like kamituel has done
// then just print each array element one by one
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
}
How about the every method?
cars.every( function(c) {
alert("car: " + c);
});
You're almost there. Since the JS code was located before the HTML, the button element still doesn't exist. Best just wrap the code with window.onload and it should work:
window.onload = function() {
document.getElementById("addCarBtn").onclick = function() {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
};
Live test case.
Edit: just noticed your button doesn't have type. This means that some browsers might make it a submit button by default, which will cause a page reload. To avoid it, make it a plain button:
<button id="addCarBtn" type="button">
I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS