Continuously change text in an element - javascript

Hi all I have the following code :
var names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
$("#pickName").on('click', function () {
//pickName();
var name = names[Math.floor(Math.random() * names.length)];
alert(name);
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>
Which when I click on the #pickName selects a name from the array and displays it in a alert box then removes it from the array and from the <ul> list. Which is all fine but what I'd like to do is have the H1 tag (#randomName) looping through and 'flashing' all of the remaining names (constantly until I click #pickName).
I've tried doing an internet search for this but I can't think of how to word what it is that I'm trying to do!
Could anyone help?

You can do it using setInterval and by keeping a global counter, also take care to take the modulo of this counter with your array length to avoid out-of-bounds indexing.
Here is the doc for setInterval. You should also assign the return value so you can later clear your interval timer.
const names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
const h1$ = $('#randomName');
let idx = 0;
setInterval(() => {
h1$.text(names[idx++ % names.length]);
}, 200);
$("#pickName").on('click', function () {
const name = names[Math.floor(Math.random() * names.length)];
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>

Just like jo_va but having names going through randomly:
var names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
function pickName()
{
return names[Math.floor(Math.random() * names.length)]
}
$("#pickName").on('click', function () {
//pickName();
var name = pickName();
alert(name);
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
setInterval(function(){
$("#randomName").text(pickName());
}, 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>
Though, I recommend you find a more sustainable way to manage your elements rather than giving the <li> ids that match their content. Unless it's really meant for static use :)

Related

How do I select elements whose class name starts with a specific word?

My goal, for example, is to select elements that have a class starting with the word "child-1".
var childs = document.querySelectorAll("#child-" + i);
This code can only select the class name "child-x".
<li class="child-1-5">
<li class="child-1-8">
<li class="child-1-9">
How do I select elements that begin with Child1?
This should work:
var childs = document.querySelectorAll("li[class^='child-1']");
If you'd like to select the first number dynamically with your parameter, just escape to the variable:
var i = 1;
var childs = document.querySelectorAll("li[class^='child-" + i + "']");
<li class="child-1-5">5
<li class="child-1-8">8
<li class="child-1-9">9
You can use CSS wildcards for that:
const children = document.querySelectorAll('[class^="child-"], [class*=" child-"]');
console.log(children);
<li class="child-1-5">
<li class="child-1-8">
<li class="child-1-9">
<li class="some classes child-1-10 to make noise">
MDN reference

radomize ul tag not working

this is probably an easy question for you guys but I'm very new to coding and can't figure out this. I have a code that I want to randomize the given choices in the questions, and I've found a script online that does that but it's not working. I don't know what the
// shuffle only elements that don't have "group" class
$ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function() {
means so I tried to put all id that I don't need to randomize in it but it's still not working.
Can someone help me this please? Also is there anyway I can add choice "A", choice "B", choice "C", and choice "D" in front of each given options so even after the options(answers) are randomized, the A,B,C,D options will still be in order? Thank you. Here's the code:
HTML:
<!DOCTYPE html>
<html>
<body>
<script src="JQ.js"></script>
<script src="function.js"></script>
<link href="style.css" rel="stylesheet" />
<div id="quiz_container">
<ul class="quiz_container">
<li class="single_question" data-question-id="1" data-correct-answer="1">
<div class="question">
<h1 class="title">P.1 Grammar Review</h1>
<p class="text">1. "What is your name__"</p>
</div>
<ul class="options">
<li value="1">?</li>
<li value="2">.</li>
<li value="3">,</li>
</ul>
<div class="result"></div>
</li>
<li class="single_question" data-question-id="2" data-correct-answer="b">
<div class="question">
<p class="text">2. "Do you like the banana__"</p>
</div>
<ul class="options">
<li value="a">.</li>
<li value="b">?</li>
<li value="c">,</li>
</ul>
<div class="result"></div>
</li>
</div>
</body>
</html>
JS:
$(document).ready(function () {
/*
* shuffles the array
* #param {Array} myArray array to shuffle
*/
function shuffleArray(myArray) {
for (var i = myArray.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
return myArray;
}
var $ul, $li, li_content, li_list;
// find all lists to shuffle
$("#quiz_container > ul").each(function () {
$ul = $(this);
li_list = [];
// shuffle only elements that don't have "group" class
$ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function () {
// add content to the array and remove item from the DOM
li_list.push($(this).html());
$(this).remove();
});
// shuffle the list
li_list = shuffleArray(li_list);
while (li_content = li_list.pop()) {
// create <li> element and put it back to the DOM
$li = $("<li />").html(li_content);
$ul.append($li);
}
});
$("#contact_div").show();
});
$(document).on('click', '.single_question .options li', function () {
// Save the question of the clicked option
question = $(this).parents('.single_question');
// Remove If Anyother option is already selected
question.find('.selected').removeClass('selected');
// Add selected class to the clicked li
$(this).addClass('selected');
// selected option value
selected_answer_value = $(this).attr("value");
// Value of correct answer from '.single-question' attribute
correct_answer_value = question.attr("data-correct-answer");
correct_answer_text = question.find('.options').find("li[value='" + correct_answer_value + "']").text();
if (correct_answer_value == selected_answer_value)
result = "<div class='correct'> Correct ! </div>";
else
result = "<div class='wrong'> Correct answer is -> " + correct_answer_text + "</div>";
// Write the result of the question
$(this).parents('.single_question').find('.result').html(result);
// Calculate the score
score_calculator();
});
/**
* It loops through every question and increments the value when "data-correct-answer" value and "option's value" are same
*/
function score_calculator() {
score = 0;
$('.single_question').each(function () {
question = $(this);
if (question.attr('data-correct-answer') == question.find('.selected').attr("value")) {
score++;
}
});
$('.correct_answers').html(score);
}
It looks like you're using jQuery, even though the question isn't tagged as such. If that's the case, you can use a code snippet written by Chris Coyier of CSS-Tricks called shuffle children.
Here's an example of the code in action.
$.fn.shuffleChildren = function() {
$.each(this.get(), function(index, el) {
var $el = $(el);
var $find = $el.children();
$find.sort(function() {
return 0.5 - Math.random();
});
$el.empty();
$find.appendTo($el);
});
};
$("ul.randomized").shuffleChildren();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Static List:</h4>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
<li>Fourth element</li>
</ul>
<h4>Randomized List:</h4>
<ul class="randomized">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
<li>Fourth element</li>
</ul>
In order to apply it to your own code, all you'd need to do is modify the CSS selector at the bottom of the jQuery snippet. In your case, ul.options might be a good choice.
Here are a couple of examples using your markup:
jsFiddle
Self-Contained HTML Doc

Group list-items into sub-lists based on a data attribute

I want to append the <li> from one <ul> to another <ul> that's created on the fly. I want to group the list-items into new sub-lists based on their data-group attribute.
<ul id="sortable1">
<li data-group="A">test</li>
<li data-group="A">test1</li>
<li data-group="B">test2</li>
<li data-group="B">test3</li>
<li data-group="C">test4</li>
</ul>
Basically I'm trying to loop through this list and grap all <li> from each group, and then move it to another <ul>.
This is what I have so far, but I'm not getting the expected results. I have done this in Excel in the past but can't get it to work with jQuery.
var listItems = $("#sortable1").children("li");
listItems.each(function (idx, li) {
var product = $(li);
//grab current li
var str = $(this).text();
if (idx > 0) {
//append li
str += str;
if ($(this).data("group") != $(this).prev().data("group")) {
//I should be getting test and test1.
//but alert is only giving test1 test1.
alert(str);
//need to break into groups
//do something with groups
}
}
});
How about something like this:
$(function() {
var sortable = $("#sortable1"),
content = $("#content");
var groups = [];
sortable.find("li").each(function() {
var group = $(this).data("group");
if($.inArray(group, groups) === -1) {
groups.push(group);
}
});
groups.forEach(function(group) {
var liElements = sortable.find("li[data-group='" + group + "']"),
groupUl = $("<ul>").append(liElements);
content.append(groupUl);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="sortable1">
<li data-group="A">test</li>
<li data-group="A">test1</li>
<li data-group="B">test2</li>
<li data-group="B">test3</li>
<li data-group="C">test4</li>
</ul>
<div id="content">
</div>
I hope I didn't misunderstand you.

jQuery: How to specify element in this case?

I have a function that adds game results to a schedule.
I want to have the score of a winning team in yellow - add ".winner" class to (<%=score1%> or <%=score2%>).
I wonder what is the correct way to specify needed element, using jQuery.
My current code isn't working. All elements get ".winner" class, regardless of whether a team won or not.
addGame: function(gameInfo) {
var sHtml = window.JST["schedule/gamelist/inner_row"](gameInfo);
var tableRow = $("<tr>").append(sHtml);
tableRow.data("id", gameInfo.id);
return tableRow;
}
addNewTable: function(date, gameInfos, number) {
...
...
for (var ind = 0; ind < gameInfos.length; ++ind) {
gameInfo = gameInfos[ind].attributes;
var element = this.addGame(gameInfo);
$("#schedule_mytable_tbody" + number).append(element);
if (gameInfo.score1 > gameInfo.score2)
$("li:nth-child(5)").find("p:first-child").addClass("winner");
else
$("li:nth-child(5)").find("p:last-child").addClass("winner");
}
My template looks like this.
window.JST["schedule/gamelist/inner_row"] = _.template(
'<td width="668px">\
<ul>\
<li class="schedule_..."></li>\
<li class="schedule_..."></li>\
<li class="schedule_...."></li>\
<li class="schedule_..."></li>\
<li class="schedule_boxscore">\
<p><%=score1%></p>\
<p><%=score2%></p>\
</li>\
...
Rendered HTML part:
<li style="font-size:16px" class="schedule_boxscore">
<p class="winner">2</p>
<p class="winner">10</p>
</li>
So, because of the "for" loop, all paragraphs get the ".winner" class, not just <p class="winner">10</p>...

get an array of data-val values from a list of elements of a certain css class

I would like to get an array of the values from the data-val attributes of .my-li elements
<ul id="stuff">
<li class='my-li' data-val='1'>
<li class='my-li' data-val='2'>
<li class='my-li' data-val='3'>
<li class='my-li' data-val='4'>
<li class='my-li' data-val='5'>
<ul>
here the result should be [1,2,3,4,5];
anybody knows a good way of doing this ?
Try:
var foo = $('#stuff .my-li').map(function () {
return $(this).data('val');
});
try this simple one.
var array = [];
$('.my-li').each(function(){
array.push($(this).attr('data-val'));
});
alert(array);
fiddle : http://jsfiddle.net/pp5pw/
var foo = $('#stuff .my-li').map(function () {
return $(this).attr('data-val');
});
console.log(foo[0])
jsfiddle goes to http://jsfiddle.net/granjoy/KxQAr/

Categories