I use code from HERE (Stackoverflow.com)
I do it for my stuff like this
var i = 0;
var links = ["http://www.example.com/page","http://www.example.com/anotherpage"];
var renew = setInterval(function(){
document.getElementById("changelink").href = links[i];
if(links.length==i){
i=0;
}else{
i++;
}
},5000);
<a id='changelink' href='http://google.bg/'>test</a>
but when the link change it writes me undefined, I try with the same code with iframe and also gives me undefined whats going on ?
Your count is off by one
var i = 0;
var links = ["http://www.example.com/page", "http://www.example.com/anotherpage"];
var renew = setInterval(function () {
document.getElementById("changelink").href = links[i];
if (links.length - 1 == i) {
i = 0;
} else {
i++;
}
}, 5000);
When links.length == i you're actually trying to get an array index that doesn't exists, so you'll have to subtract one and do links.length - 1 == i
Related
In my script the computer clicks through contact tabs in WhatsApp Web and for each checks whether the person is online or not. This is done with a loop, which starts again when contact number 16 is reached. Anyhow, the loop doesn't work and the variable 'i' doesn't increase. This is strange, since if I replace selectContact(${i}) by console.log, the increment works. Maybe the ${} prevents the i from updating?
var i = 1
setInterval(function () {
selectContact(`${i}`)
if (document.getElementsByClassName("O90ur")[0] !== undefined) {
var online = document.getElementsByClassName("O90ur")[0].innerHTML
if (online == "online") {
console.log(`${i}`)};
}
i = i % 16 + 1
}, 1000);
Here is the code for selectContact, if the issue should lie within here.
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
contacts = [];
chat_div = [];
function triggerMouseEvent(node, eventType) {
var event = document.createEvent('MouseEvents');
event.initEvent(eventType, true, true);
node.dispatchEvent(event);
}
function getChatname(){
$("#pane-side > div > div > div").find("._2FBdJ > div._25Ooe").each(function(){
contacts.push($(this).text());
chat_div.push($(this));
})
}
function selectContact(name){
getChatname()
for (i = 0; i < contacts.length; i++){
if (name.toUpperCase() === contacts[i].toUpperCase()){
triggerMouseEvent(chat_div[i][0],"mousedown")
}
}
}
You've missed out the var statement declaring i in your for loop, meaning it overwrites your global i.
function selectContact(name){
getChatname()
for (var i = 0; i < contacts.length; i++){
if (name.toUpperCase() === contacts[i].toUpperCase()){
triggerMouseEvent(chat_div[i][0],"mousedown")
}
}
}
I'm trying to add the numbers of pagination using Javascript. The arrows navigation is working fine but when I try to add the numbers of pages my code doesn't work. I have 2 pages with 10 results each. When I click in the number 1 the console print the number 3. The problem is inside the function createPagination when I create the loop for the page numbers. Any help?
var arrFull = [];
var pageSize = 10;
var pages = -1;
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
number.addEventListener('click', function(event) {
event.preventDefault();
changePagination(pagination);
console.log(pagination);
});
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
When you pass on your pagination variable it passes the last value set to it in that context (the 3 because of its last iteration in the loop).
You should declare a variable inside the click event and assign to it the value of pagination and then pass your local variable to your method:
number.addEventListener('click', function(event)
{
let currentPage = pagination;
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
That should do the trick.
Edit
This is the actual solution:
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
The reason why the number 3 is being returned is because the let currentPage = pagination; line is being executed when the event triggers; by that time the value of the variable pagination is equal to 3, so you need to save its value through every iteration (it can be saving it inside a property within your element outside of the event scope like so: number._pageNumber = pagination;; or as the given example: number.setAttribute("page", pagination);).
Full implementation
<html>
<body>
<!--Element to simulate the pagination-->
<div id="pagination"></div>
<script>
var arrFull = [];
var pageSize = 10;
var pages = 2; // Change to simulate your case (changed the '-1' to '2')
var actualPage = 0;
function changePagination(pagination) {
if(Number(pagination) !== actualPage && pagination > 0 && pagination <= pages) {
var start = ((pagination - 1) * pageSize) + 1;
if(pagination === 1) {
ini = 0;
}
var end = pagination * pageSize;
if(end > arrFull.length) {
end = arrFull.length;
}
var arr = arrFull.slice(start,end);
for(var i = 0; i < arr.length; i++) {
createObject(arr[i]);
}
actualPage = Number(pagination);
createPagination();
}
}
function createPagination() {
var paginator = document.getElementById('pagination');
paginator.innerHTML = "";
var arrowLeft = document.createElement('a');
arrowLeft.setAttribute('href', '');
var arrowRight = document.createElement('a');
arrowRight.setAttribute('href', '');
arrowLeft.innerHTML = '<span class="arrow"></span>';
arrowLeft.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage - 1);
});
arrowRight.innerHTML = '<span class="arrow"></span>';
arrowRight.addEventListener('click', function(event) {
event.preventDefault();
changePagination(actualPage + 1);
});
paginator.appendChild(arrowLeft);
for(var pagination = 1; pagination <= pages; pagination++) {
var number = document.createElement('a');
number.setAttribute('href', '');
number.innerHTML = pagination;
// <Here_is_the_sugested_code> //
number.setAttribute("page", pagination);
number.addEventListener('click', function(event) {
let currentPage = +event.target.getAttribute("page");
event.preventDefault();
changePagination(currentPage);
console.log(currentPage);
});
// </Here_is_the_sugested_code> //
paginator.appendChild(number);
}
paginator.appendChild(arrowRight);
}
createPagination(); // Call to the function to simulate the generation
</script>
</body>
</html>
Example
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
setInterval (function(){
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
I'm trying to have this typing "enter" effect and I am wondering how to make it only go once. So it will type out "ENTER..." and then stop.
Example
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
(function nextLetter() {
enter.innerHTML = text.substr(0, ++i);
if (i < text.length) {
setTimeout(nextLetter, 200);
}
})();
edit: you either have to use setTimeout (one time "sleep"), or remember return value of setInterval and destroy that timer by clearInterval after you don't need it/want it running.
If you use interval, you have to stop the it with clearInterval. Stop it inside the interval function, which is declared as a variable, in the if-statement:
var text = 'ENTER...';
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval(function() {
enter.innerHTML += text[i];
i += 1;
if(i === text.length) {
clearInterval(interval);
}
}, 200);
JSFiddle
var text = 'ENTER...';
var chars = text.split('');
var enter = document.getElementById("enter")
var i = 0;
var interval = setInterval (function(){
if(i == chars.length) {
clearInterval(interval);
return;
}
if (i < chars.length){
enter.innerHTML += chars[i++];
}else{
i = 0;
enter.innerHTML = "";
}
}, 200);
<div id="enter"></div>
So, I have a code here that works perfectly fine when I am viewing it in the active browser tab. But, as soon as I minimize or switch between other tabs of the browser (which is chrome by the way) the code starts giving issues. Here is the code below:
var a = document.getElementById("slidermain");
var b = a.getElementsByTagName("IMG");
var len = b.length;
var noOpac = 0;
var fullOpac = 10;
var imgNumb = 0;
function initFade(count){
imgNumb = imgNumb + count;
if(imgNumb < 0){
imgNumb = len;
}
if(imgNumb > len){
imgNumb = 1;
}
elem = b[imgNumb-1];
startFadeEffect(elem);
}
function startFadeEffect(elem){
var opacSetting = noOpac / 10;
if(noOpac > 10){
opacSetting = 1;
}
elem.style.opacity = opacSetting;
elem.style.display = "block";
noOpac++;
var timer = setTimeout(function() { startFadeEffect(elem); }, 55);
if(opacSetting == 1){
clearTimeout(timer);
elem.style.opacity = 1;
noOpac = 0;
setTimeout(function() { endFadeEffect(elem); }, 2000);
}
}
function endFadeEffect(elem){
var opacSetting = fullOpac / 10;
if(fullOpac < 0){
opacSetting = 0;
}
elem.style.opacity = opacSetting;
fullOpac--;
var timer = setTimeout(function() { endFadeEffect(elem); }, 55);
if(opacSetting == 0){
clearTimeout(timer);
elem.style.opacity = 0;
elem.style.display = "none";
fullOpac = 10;
return false;
}
}
function autoFade(){
var loop = setInterval("initFade(1)", 4000);
}
Please not that I have been looking on this site for the answer, but mostly the ones I have found are JQuery based solutions; however, I am looking for a JavaScript only solution in which I might not have to use the get new date function. Please do not mark my question as duplicate as I have done good research. Thanks!
This is not a problem with your javascript, but with Chrome. Chrome does some weird things with your tabs when they aren't active. Add code to "fix the mess", or account for not the tab being active, to recover after tabbing out and back in.
I tried to count an element clicks, and, in the right number call some action.
var count = 0;
document.getElementById("rolarbaixo").onClick = function(e) {
if( count >= 3 ) {
var elem = document.getElementById("noticia");
elem.setAttribute("style","top: 0px;");
}
else {
count ++;
}
};
When i clicked 3 times in the link "rolarbaixo" the div "noticia" set the "top: 0px;", but this doesn't work.
Why?
count ++ should be count++. If you press F12, you will be able to get to the developer tools and debug the javascript.
It's onclick in lowercase
var count = 0;
document.getElementById("rolarbaixo").onclick = function (e) {
if (count >= 2) {
var elem = document.getElementById("noticia");
elem.style.top = "0px";
} else {
count++;
}
};
FIDDLE
And it's >= 2 for three clicks (zero based and all).
AS the question is tagged jQuery, this would be it
$('#rolarbaixo').on('click', function() {
var clicked = $(this).data('clicked') || 0;
if (clicked >= 2) $('#noticia').css('top', 0);
$(this).data('clicked', ++clicked);
});
FIDDLE
Misprint in else statement and change onclick to lowercase:
var count = 0;
document.getElementById("rolarbaixo").onclick = function(e) {
if( count >= 3 ) {
var elem = document.getElementById("noticia");
elem.setAttribute("style","top: 0px;");
} else {
count++;
}
};