Javascript content rotator? - javascript

I’ve got the basics of a content rotator done, the only problem is it doesn’t loop itself back to the beginning and I cannot figure out why! It is a very simple javascript script:
window.onload = function() { setInterval("transition()", 5000); }
function transition()
{
var y = document.getElementById("featured").getElementsByTagName("li");
for (var i=0;i<y.length;i++)
{
if (y[i].className == "current")
{
y[(i+1)].className = "current";
y[i].className = "";
break;
}
}
}
It keeps stopping at the end of the list, basically I just want it to loop. Any help?

You can make this a little smarter by taking advantage of the wonderful language that is Javascript:
window.onload = function() {
var y = document.getElementById('featured').getElementsByTagName('li');
var ylen = y.length, index = 0;
y[0].className = 'current';
setInterval(function() {
y[index].className = '';
index = (index + 1) % ylen;
y[index].className = 'current';
}, 5000);
};
When you pre-define the list of <li> elements like that, the function you provide for the interval timer can reference them every time the timer fires. The index variable increments up until it hits the end of the array, and then it'll be set back to zero.

try this:
if (y[i].className == "current")
{
if (y[i+1]]
y[i+1].className = "current";
else
y[0].className = "current";
y[i].className = "";
break;
}

First time you loop you set the last elements class "current". You should put something like
y[0].className = "current"
when you reach and of the loop.

Related

How to Change innerHTML on Interval pulling from an array?

Trying to get an element to change every x number of seconds. When I click the button it should change the innerHTML, looping through an array. The code below changes the text but displays the last result in the array.
<h1 id="header">Agent</h1>
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
function changeText() {
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var text = "";
var i = 0;
var x = document.getElementById("header");
for (i = 0; i < headers.length; i++) {
text = headers[i];
x.innerHTML = text;
}
}
</script>
Move the count outside of the function, and then keep looping round and resetting to 0 when at end.
function loopHeader() {
var loopHeader = setInterval(changeText, 1000);
}
var headers = ["Agent", "Expert", "Homes", "Service", "Results"];
var loopItem = 0;
function changeText() {
loopItem++;
if (loopItem == headers.length) {
loopItem = 0;
}
document.getElementById("header").innerHTML = headers[loopItem];
}
</script>
<div id="header">
</div>
<button id="change-header" onclick="loopHeader()">Click Me</button>
That's because every time you changeText is called it start changing the innerHTML of the button by the text from the array all from index 0 to the end (It's happening you just can't see it because it's happening fast). What you need is to define i outside the function and every time the function is called increment i and show its corresponding value from the array without a loop. Like this:
<button id="change-header" onclick="loopHeader()">Click Me</button>
<script>
function loopHeader() {
// if you want to start the animation just after the button is clicked, then uncomment the next line
// changeText();
var loopHeader = setInterval(changeText, 1000);
}
var i = 0; // i declared outside with the initiale value of 0
var headers = ["Agent", "Expert", "Homes", "Service", "Results"]; // this also should be outside (what's the point of redefining it every time the function is called)
function changeText() {
var x = document.getElementById("change-header"); // the id is change-header
// increment i and check if its beyond the boundaries of the loop, or just use modulo operator t prevent it from going beyond
i = (i + 1) % headers.length;
x.textContent = headers[i]; // textContent is better than innerHTML
}
</script>

JavaScript clearInterval

I'd like to have a div become visible on a button click and have a setInterval append periods to show loading. I would also like a button to clear that interval and hide the div that shows up.
here's a fiddle
http://jsfiddle.net/4qx4r/4/
here's code:
function ProgressBar(){
var div;
var start = function(){
var count = 0,
div = $('#divNotification').show().text('Uploading').css('align','center'),
originalText = div.text(),
count = 0;
var beginCount = setInterval(function(){
var newText = div.text() + '.';
div.text(newText);
count++;
if(count > 5){
div.text(originalText);
count =0;
}
console.log(count);
},500)
}
var stop = function(){
console.log('stop');
div.hide();
window.clearInterval(beginCount);
}
this.start = start;
this.stop = stop;
}
var progressBar = new ProgressBar();
$('#btnStart').click(function(){
progressBar.start();
});
$('#btnStop').click(function(){
progressBar.stop();
});
Currently when I click btnStop I get `cannot read property hide of undefined'. How can I make this stop the interval and hide the div?
You are setting var beginCount within a function, therefore that variable is only accessible within that function.
Try declaring that variable outside or simply just remove the var part.
I would add it next to var div declaration
Also you need to replace commas with semicolons and your div is not set to the object, try the following:
var count = 0;
div = $('#divNotification');
div.show().text('Uploading').css('align','center');
originalText = div.text();
count = 0;
http://jsfiddle.net/4qx4r/6/
this works: http://jsfiddle.net/W8ySn/3/
I separated the initial div assignment:
div = $('#divNotification');
var count = 0;
div.show().text('Uploading editor').css('align','center');
originalText = div.text();
count = 0;

Simulate the look of typing, not the actual keypresses, in javascript

I'm trying to write a simple function that will make it appear as though someone is typing in a textarea
-- This is my function (forgive me if its atrocious, but I don't normally use javascript) ---
The console.log() part works fine, but for some reason I cannot get this script to update the dom the way I would expect...
function type(string) {
value = "";
el = document.getElementById("typeArea");
for (var i = 0; i < string.length; i++) {
value += string[i];
//$("#fbw > textarea").val(value);
el.textContent = value;
console.log(value);
sleep(160);
}
sleep(2000);
}
I appreciate any insight you can give me.
jsFiddle Demo
All you were missing was a construct instead of Sleep. The js approach for accomplishing this is to use a timeout and a recursive call in order to iterate through your string
function type(string,element){
(function writer(i){
if(string.length <= i++){
element.value = string;
return;
}
element.value = string.substring(0,i);
if( element.value[element.value.length-1] != " " )element.focus();
var rand = Math.floor(Math.random() * (100)) + 140;
setTimeout(function(){writer(i);},rand);
})(0)
}
You can do something like this using setTimeout function.
Codepen
$(function(){
simulateTyping('looks like someone is typing...', '#txt')
function simulateTyping(str, textAreaId) {
var textArea = $(textAreaId);
var currentCharIndex = 0;
function typeChar(){
if (currentCharIndex >= str.length)
return;
var char = str[currentCharIndex];
textArea.val(textArea.val() + char);
currentCharIndex ++;
setTimeout(typeChar, 500);
}
typeChar();
}
})

How to disable buttons after x amount of clicks in js?

I am trying to use Javascript to disable a button after it is clicked x amount of times. For simplicity sake lets say x = 2 for now. I cannot seem to get the counter to increment. Thank You for any help!
var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
coke.onclick = function(){
var count =0;
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}
Where "coke" is the element ID. If i get rid of the if statement and just have coke.disabled = true, of course it works and disables after one click. I'm sure there is a core concept I am missing.
Thank You
This is happening because each time the onclick event is fired, your var count is being assigned to 0, so it will never be greater than or equal to one in your function. If you initialize the count var outside of the onclick function, it will behave as expected.
window.onload = function () {
var count = 0;
coke.onclick = function(){
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}
You need to define count outside the scope of your onclick function:
var $ = function (id) {
return document.getElementById(id);
}
var count = 0; // set initial count to 0
window.onload = function () {
coke.onclick = function(){
if (count >= 1)
{
coke.disabled = true;
}
else
count++;
};
}

Can we get radiobuttonList.Items.Count in .aspx page

Can we get the count of total radiobuttonlist items from .aspx page. I have to call a javascript function onclientclick of a button and i want to loop through the total number of radiobuttonlist items. So can anyone tell me that can we get it from .aspx page. Because in my scenario i can not use code behind for this.
function ClearRBL() {
for (i = 0; i < RBLCOUNT; i++) {
document.getElementById('rblWorkerList_' + [i]).checked = false;
}
}
How can i get RBLCOUNT here from .aspx page only? If not possible then in Javascript please.
I don't know how the aspx side would work, but if you want to do it just in JavaScript you could do something like the following that doesn't need to know the total number of elements in advance:
function ClearRBL() {
var i = 0,
rbl;
while (null != (rbl = document.getElementById('rblWorkerList_' + i++)))
rbl.checked = false;
}
The above assumes that the element ids end in numbers beginning with 0 counting up by 1s; the while loop will keep going until document.getElementById() doesn't find a matching element (in which case it returns null). A less cryptic way of writing it is as follows:
function ClearRBL() {
var i = 0,
rbl = document.getElementById('rblWorkerList_' + i);
while (null != rbl) {
rbl.checked = false;
i++;
rbl = document.getElementById('rblWorkerList_' + i);
}
}
P.S. When the while loop finishes i will be equal to the number of radio buttons, which may be useful if you want to do something with that number afterwards.
Try this:- This is not exactly what you want but hope it will help you.
function GetRBLSelectionID(RadioButtonListID) {
var RB1 = document.getElementById(RadioButtonListID);
var radio = RB1.getElementsByTagName("input");
var isChecked = false;
var retVal = "";
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
retVal = radio[i].id;
break;
}
}
return retVal;
}
you can give a name all radio button and then get them like this.
var RBLCOUNT= document[groupName].length;
or
var RBLCOUNT= 0;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
if(inputs[i].type =="radio"){
RBLCOUNT++;
}
}
I just created a javascript function as mentioned by Karthik Harve and found the total number of rows generated dynamically as below: -
function ClearRBL() {
var rblLen = document.getElementById('rblWorkerList');
for (i = 0; i < rblLen.rows.length; i++) {
document.getElementById('rblWorkerList_' + [i]).checked = false;
}
}
It's working on both Mozila and IE.
Thanks alot to all who tried to help.

Categories