All Imtrying to do is have a loop to iterate over my nav elements, and every second check the data-time to the variable being counted, and change a div to have the text within the list item. Ill already have the list in increasing order so that wont be a issue.
Ive tried 40 different ways to do this and this is my cloest to working solution, it just sets the innerHTML of the div to whitespace and I dont now why.
<DOCTYPE! Html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var navList = document.getElementsByClassName("nav");
var y = 0;
for(x = 0; x< 50; x++){
var timeCheck = navList[y].getAttribute("data-time");
setTimeout(function(){
if (timeCheck == x){
document.getElementById('itemHtml').innerHTML = navList[y].innerHTML;
y++;
}
},1000);
}
});
</script>
</head>
<body>
<ul>
<li class="nav" data-time="4"> test 1</li>
<li class="nav" data-time="8"> test 2</li>
<li class="nav" data-time="14"> test 3</li>
<li class="nav" data-time="18"> test 4</li>
</ul>
<div>
<h3 id="itemHtml"> placeholder </h3>
<h3 id="test"> placeholder </h3>
</div>
</body>
</html>
By the time your setTimeout executes, the for loop has most likely already gone through all elements. Also it creates a closure, so the x values will not be what you expect it to be. Last but not least, setTimeout executes once after the specified time, you want to use setInterval.
So what you are trying to do is check every second if time has eclipsed up to that date-time of any element? If so use an interval not a set timeout. Also have the loop within each execution of the interval.
var navList = document.getElementsByClassName("nav");
var y = 0;
var timeCount = 0;
setInterval(function(){ // Create an interval with a function payload.
timeCount++; // Increment the times hit. This is an an approx of number of seconds
for(x = 0; x< navList.length; x++){
var timeCheck = navList[y].getAttribute("data-time");
console.log('timeCheck: ' + timeCheck + ' timeCount ' + timeCount);
if(timeCheck == timeCount){ // Have we found a match for this current second?
console.log('found a match');
console.log(navList[y].innerHTML);
document.getElementById('itemHtml').innerHTML = navList[y].innerHTML;
y++;
}
}
}, 1000); // run interval every second.
http://jsfiddle.net/3pop4g76/4/
What I ended up using for those interested.
<DOCTYPE! Html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var navList = document.getElementsByClassName("nav");
var y = 0;
var x = 0;
var test = setInterval(function(){
x++;
var timeCheck = navList[y].getAttribute("data-time");
if (timeCheck == x){
document.getElementById('itemHtml').innerHTML = navList[y].innerHTML;
y++;
}
if(x == 10){clearInterval(test)}
},1000);
});
</script>
</head>
<body>
<ul>
<li class="nav" data-time="4"> test 1</li>
<li class="nav" data-time="8"> test 2</li>
<li class="nav" data-time="14"> test 3</li>
<li class="nav" data-time="18"> test 4</li>
</ul>
<div>
<h3 id="itemHtml"> placeholder </h3>
<h3 id="test"> placeholder </h3>
</div>
</body>
</html>
Related
Linking Java Script and html-- Script (javascript) that shuffles the list of items (html)...works on here but not locally when I try to run
The code works when I use the console on this website when I went to post the code,but when I run through notepad++ in chrome...The program does not work. I am not sure why it would appear to work on here, but not on my local machine?
$(".btn").click(function() {
var $nodes = $("#Items").find("li");
shuffle($nodes, "Switch");
$("#Items").append($nodes);
});
//Function that will shuffle only your switchable elements.
function shuffle(nodes, switchableSelector) {
var length = nodes.length;
//Create the array for the random pick.
var switchable = nodes.filter("." + switchableSelector);
var switchIndex = [];
$.each(switchable, function(index, item) {
switchIndex[index] = $(item).index();
});
//The array should be used for picking up random elements.
var switchLength = switchIndex.length;
var randomPick, randomSwap;
for (var index = length; index > 0; index--) {
//Get a random index that contains a switchable element.
randomPick = switchIndex[Math.floor(Math.random() * switchLength)];
//Get the next element that needs to be swapped.
randomSwap = nodes[index - 1];
//If the element is 'not switchable', ignore and continue;
if($(randomSwap).hasClass(switchableSelector)) {
nodes[index - 1] = nodes[randomPick];
nodes[randomPick] = randomSwap;
}
}
return nodes;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>List of Items</h2>
<ul id="Items">
<li class="Switch">Item 1</li>
<li class="Switch">Item 2</li>
<li class="Switch">Item 3</li>
<li class="Switch">Item4</li>
<li class="Switch">Item 5</li>
<li class="Switch">Item 6</li>
</ul>
<input type="button" class="btn" value="Shuffle" />
It is the order of things: your code snippet tries to hook the click handler on the button right when it loads. However if you have the 'traditional' file layout, you have some <script> tag(s) first, and then the <body>. So when the $(".btn").click(function(){...}); part runs, the given <button> does not exist (yet), and you do not even get an error, because it is a class-selector, which is perfectly valid to produce an empty result.
Put the click-binding part into a function, and call it from onload, then it works:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startup(){
$(".btn").click(function() {
var $nodes = $("#Items").find("li");
shuffle($nodes, "Switch");
$("#Items").append($nodes);
});
}
//Function that will shuffle only your switchable elements.
function shuffle(nodes, switchableSelector) {
/* unchanged */
}
</script>
</head>
<body onload="startup()">
<h2>List of Items</h2>
<ul id="Items">
<!-- truncated as it is not an example which could run here anyway -->
</ul>
<input type="button" class="btn" value="Shuffle" />
</body>
</html>
On StackOverflow the code works, because the <script> part is located at the end of <body> (you can check it with right-click on your own example and "View frame source", at least in Chrome, but that is the browser you have mentioned). That is also a possible and legal layout, some people like it some others do not, it certainly cures this kind of issues.
You may clear cache memory of chrome and run it again
I’m trying to get my head around Event’s and I’m totally lost? I would like to access an elements id from an event listener, using e.path Array? The id that I want is always in the article id=”someID” node of the objTmp Array().
I also can figure out why this only works in Chrome all other browsers say that objTmp is undefined?
Any help would be appreciated...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Working </title>
<style type="text/css">
</style>
<script type="text/javascript">
function init() {
var eventTmp = document.querySelectorAll("ul li");
for (var i = 0; i < eventTmp.length; i++) {
eventTmp[i].addEventListener('click', function (e) {
var objTmp = e.path;
for (var i = 0; i < objTmp.length; i++) {
if (objTmp[i].tagName === "ARTICLE") {
//This is where I get lost
//How do I get the id from this node??
var x = objTmp[i];
console.log(x);
}
}
e.stopPropagation();
}, false);
}
}
</script>
</head>
<body onload="init()">
<main id="">
<article id="id_Article0">
<section>
<h2>Header</h2>
<div>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
</section>
</article>
<article id="id_Article1">
<section>
<h2>Header</h2>
<div>
<p>
<h3>Some Text</h3>
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</p>
</div>
</section>
</article>
</main>
</body>
</html>
Here's a way to locate the ancestor ARTICLE node without using event.path:
function init() {
var eventTmp = document.querySelectorAll("ul li");
for (var i = 0; i < eventTmp.length; i++) {
eventTmp[i].addEventListener('click', function (e) {
var articleNode = this;
while (articleNode.nodeName != "ARTICLE" && articleNode.nodeName != "BODY") {
articleNode = articleNode.parentNode;
}
if (articleNode.nodeName == "BODY") {
// no article ancestor was found
} else {
// do something with articleNode
console.log(articleNode.id);
}
e.stopPropagation();
}, false);
}
}
Ive had better luck with:
e.target.id
If there's multiple targets then:
e.target[i].id
A bigger problem Im seeing is that both your outter for loop and your nested for loop have the same counter variable i.
You'd want to give the inner for loop a different counter variable.
I have a big list <li> of items and a button to "shuffle" the list, what I'm trying to achieve is, show only 3 RANDOM list items when the page loads, then on button click, shuffle the list, hide the current 3 list items and show OTHER RANDOM list items.
What I did till now is this, but it doesn't really do everything I'm trying to achieve, I get 3 items showed only, but they get randomised between the same 3 list items always...
$('.fr_revs > li').hide().filter(':lt(3)').show();
var ul = document.querySelector('.fr_revs');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}
Can somebody help me please. Thank you
Try something like this
var ul = $('ul'),
lis = ul.find('li').detach(),
button = $('#shuffle'),
used = [];
function showRandom() {
var new_lis = [];
while (true) {
var li = lis[Math.floor(Math.random() * lis.length)];
if (used.indexOf(li) === -1 && new_lis.indexOf(li) === -1) new_lis.push(li);
if (new_lis.length >= 3) break;
}
used = new_lis;
ul.html(new_lis);
}
button.click(showRandom);
showRandom();
You need to have six or more <li> elements, otherwise it will be an infinite while (true) loop.
Hide all items at first. Then generate 3 random number and select item with index using .eq() and show selected items.
$(".fr_revs > li").hide();
randomItem();
$("button").click(function(){
var lastItems = $(".fr_revs > li:visible");
randomItem();
lastItems.hide();
});
function randomItem(){
for (var i = 0; i < 3; i++){
var length = $(".fr_revs > li:not(:visible)").length;
var random = Math.floor(Math.random() * length);
$(".fr_revs > li:not(:visible)").eq(random).show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Get new</button>
<ul class="fr_revs">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
<li>I</li>
<li>J</li>
<li>K</li>
<li>L</li>
<li>M</li>
<li>N</li>
<li>O</li>
</ul>
try this simple answer, it is very easy and here is the working demo
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
</style>
<body>
<input type="button" value="click to shuffle" id="shuffle">
<ul class="mylist">
<li id="id1">one</li>
<li id="id2">two</li>
<li id="id3">three</li>
<li id="id4">four</li>
<li id="id5">five</li>
<li id="id6">six</li>
<li id="id7">seven</li>
<li id="id8">eight</li>
<li id="id9">nine</li>
<li id="id10">ten</li>
<li id="id11">eleven</li>
<li id="id12">twelve</li>
</ul>
</body>
<script type="text/javascript">
$(document).ready(function(){
$("ul.mylist li").slice(3).hide();
var theCount = 3;
$("#shuffle").click(function(){
$("ul.mylist li").hide();
var theLength = $("ul.mylist li").length;
if(theCount == theLength)
{
theCount = 3;
}
else
{
theCount = theCount + 3;
}
$("ul.mylist li").slice(theCount-3,theCount).show();
});
});
</script>
</html>
note: in here, length(number of elements inside the ul) should be a number which can devide from 3, because you want to show 3 per time
After researching:
Changing images on hover
is about the closest found to something that helped me. It didn't help much. I don't have any formal web experience. So, anyone who does, it would be beyond appreciated to a) fix my issue, but b) to actually know why this thing is not shuffling images..
So this is where I'm at in my HTML:
<div class="navBar" id="myNavBar">
<ul id="navOptions">
<li> <img id="logo"
src="images/logo.png"
onmouseover="hoverFunction(this);" ></li>
<li class="active">Home</li>
<li>News</li>
<li>Contact</li>
<li>About</li>
</ul>
</div>
My JavaScript:
function hoverFunction(element) {
var images = ["images/logo.png",
"images/logo_2.png",
"images/logo_3.png",
"images/logo_4.png",
"images/logo.png"];
for(var i=0; i < images.length; i++){
$(element).attr("src",images[i]);
}
//element.setAttribute('src', 'images/logo_2.png');
}
Any advice?
What you appear to want is to, while the <img> is hovered, periodically change the image. Generally, this will be done by starting an interval timer, using setInterval(), when you receive the mouseenter event. The function that would be called each time the interval fires changes to the next image. When you receive the mouseout event, you would then stop the interval timer, using clearInterval().
The following code will cycle through images while the mouse hovers over the <div>:
var images = ["http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a",
"http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-icon.png?v=93426798a1d4",
"http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/sf/sf-icon.png?v=6c3100d858bb",
"http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/su/su-icon.png?v=0ad5b7a83e49"
];
var curImageIndex = 0; // 0 is displayed by default
var intervalId; //Remember the ID of the interval so we can stop it later.
function startImageCycle(el){
cycleImage(el); //Cycle the image now so feels responsive. Remove if not wanted.
intervalId = setInterval(cycleImage,1000,el); //Change image every 1000ms (1s)
}
function stopImageCycle(el){
clearInterval(intervalId);
}
function cycleImage(element){
curImageIndex++;
if(curImageIndex >= images.length) {
curImageIndex = 0;
}
$(element).attr("src", images[curImageIndex]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navBar" id="myNavBar">
<ul id="navOptions">
<li>
<img id="logo" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"
onmouseenter="startImageCycle(this);" onmouseout="stopImageCycle(this);"
</li>
<li class="active">Home
</li>
<li>News
</li>
<li>Contact
</li>
<li>About
</li>
</ul>
</div>
To achieve expected result, use counter
var counter=1;
function hoverFunction(element) {
counter++
var images = ["http://www.w3schools.com/css/img_fjords.jpg",
"http://www.w3schools.com/css/img_forest.jpg",
"http://www.w3schools.com/css/img_lights.jpg",
"http://www.w3schools.com/css/img_fjords.jpg",
"http://www.w3schools.com/css/img_forest.jpg"];
$(element).attr("src",images[counter]);
if(counter ==5){
counter=1;
}
//element.setAttribute('src', 'images/logo_2.png');
}
http://codepen.io/nagasai/pen/jAZogO
option2:updated codepen
http://codepen.io/nagasai/pen/WxYwvK
I'm trying to get all visible elements from list, but I can't find the way.
I have list
<ul id="posts">
<li style="display:none">1</li>
<li style="display:none">2</li>
<li>3</li>
<li style="display:none">4</li>
<li>5</li>
<li style="display:none">6</li>
<li>7</li>
<li>8</li>
</ul>
and I want to get every second visible element and add class "visible" to it.
I want this result
<ul id="posts">
<li style="display:none">1</li>
<li style="display:none">2</li>
<li>3</li>
<li style="display:none">4</li>
<li class="visible">5</li>
<li style="display:none">6</li>
<li>7</li>
<li class="visible">8</li>
</ul>
I tried something like this
var jQuerylistItems = jQuery('#posts').children('li');
jQuerylistItems.filter(':visible').addClass('visible');
and it works, but not right, somethimes add class, sometimes not, I'm not sure why.
Can somebody help me please?
Thanks
I would suggest using something like the following:
jQuery('#posts > li:visible:odd').addClass('visible');
Checkout out the demo here.
you can try .each();
$(document).ready(function(){
$('ul > li').each(function(){
if($(this).is(':visible')){
$(this).addClass('visible');
}
});
});
Demo
Here's solution for you. And also demo on fiddle
(function() {
'use-strict';
var el = document.getElementsByTagName('li');
for(var i=0;i<el.length;i++) {
if(!el[i].style.display && i%2 !== 0) {
el[i].className = 'visible';
}
}
}());
Modify the addClass() to use a callback and the first argument of callback is index
jQuerylistItems.filter(':visible').addClass(function(i) {
return i % 2 == 1 ? 'visible' : null;
});
My understanding is only add this class to every other visible element.
You will also need to remove this class before running it again which could be the part of the problem you are encountering
DEMO
Here's one solution: http://jsfiddle.net/5op0wzv9/.
$('ul > li:visible').each(function(index){
$(this).addClass(index % 2 === 1 ? "visible" : "");
});
I dont know if this is what you want, but here you go!!. Hope it helps.
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> MY TEST </title>
<meta charset = 'utf-8'>
</head>
<body>
<ul id="posts">
<li style="display:none">1</li>
<li style="display:none">2</li>
<li>3</li>
<li style="display:none">4</li>
<li>5</li>
<li style="display:none">6</li>
<li>7</li>
<li>8</li>
</ul>
<script>
var visibleElements = [];
var allListElements = document.getElementsByTagName('li'); // Get the reference to al the "li" elements
var index;
// Check for each element in array if his display its diferent to "none", if true, add that element to the array "visibleElements"
for (index = 0; index < allListElements.length; index++){
if(allListElements[index].style.display != 'none'){
visibleElements.push(allListElements[index]);
}
};
//Adding the class
for (var index2 in visibleElements){
visibleElements[index2].className = 'visible';
console.log('VISIBLE') // Check if adding the class name is working, if console shows 4 "VISIBLE" then its OK.
}
</script>
</body>
</html>