Counter if word appears in div [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Take a look at my jsfiddle first.
Now, I want to create a counter everytime Scissor, Rock and Paper appears in the div #myChoice.
I have to do it like this.. so no other ways like on click whatever please.
How to do this?
if "Rock" appears in the div #myChoice
-> Rock Count: 1
-> Paper Count: 0
-> Scissor Count: 0
if "Scissor" appears in the div #myChoice
-> Rock Count: 1
-> Paper Count: 0
-> Scissor Count: 1
if "Rock" appears in the div #myChoice AGAIN
-> Rock Count: 2
-> Paper Count: 0
-> Scissor Count: 1
Thanks for your help & sorry for my latest question that nobody understood lol

Use Event delegation to handle clicks. If the user clicks on an option, then look for an associated count element and update the count. The example below uses .hasClass() to see if the element clicked on has a class name option (added to distinguish the options from other elements), parseInt() to check for a number in the count container and then isNaN() to check if the count number is actually a number (unlike an empty string).
$(document).ready(function() {
$(document).click(function(event) {
if ($(event.target).hasClass('option')) {
$('#myChoice').text(event.target.innerText);
var countElement = $('#' + event.target.id + 'Count');
if (countElement.length) {
var count = parseInt(countElement.text(), 10);
if (isNaN(count)) {
count = 0;
}
countElement.text(++count);
}
}
});
});
#myChoice {
width: 100px;
height: 20px;
border: 1px solid black
}
li {
width: 50px;
border: 1px solid black;
padding: 3px;
margin-bottom: 5px
}
li:hover {
background-color: gainsboro;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div id="scissor" class="option">Scissor</div>
</li>
<li>
<div id="rock" class="option">Rock</div>
</li>
<li>
<div id="paper" class="option">Paper</div>
</li>
</ul>
<br />
<div id="myChoice">
</div>
<br />
<div id="counter">
<p>Scissor Count:
<span id="scissorCount"></span>
</p>
<p>Rock Count:
<span id="rockCount"></span>
</p>
<p>Paper Count:
<span id="paperCount"></span>
</p>
</div>

Is this what you want ?
var helloLength = $('#container:contains("Hello")').length;
if(helloLength >= 1) {
$("#counter").text("Hello " + helloLength + " times");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"> Hello </div>
<div id="counter"> Hello: /*here the number*/ times </div>
If you want to count the number of hello, you should use class instead of id: like this:
var helloLength = $('.container:contains("Hello")').length;
if(helloLength >= 1) {
$("#counter").text("Hello " + helloLength + " times");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"> Hello </div>
<div class="container"> Hello </div>
<div class="container"> Random div </div>
<div class="container"> Hello </div>
<div class="container"> Hello </div>
<div id="counter"> Hello: /*here the number*/ times </div>

You can achieve this by using a regular expression and the match() method to find the number of occurrences of 'Hello' within your string. From there you can use text() on a span within the #counter element to show the value. Try this:
var re = /hello/gi;
var count = ($('#container').text().match(re) || []).length;
$('#counter .count').text(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"> Hello hello </div>
<div id="counter"> Hello: <span class="count"></span> times </div>

I just want to count +1 inside of a div everytime the other div contains the word Hello.
I took this to mean you want to count the number of times the word "Hello" is in the first div, so here's a simple loop to do that.
// create an array out of the text of #container using spaces to delimit
var text = $('#container').text().split(" ");
var count = 0;
// loop through the array of text and check to see if each word is "Hello"
for (var i = 0; i < text.length; i++) {
if (text[i] === "Hello") {
count++;
}
}
$('#counter').text("Hello: " + count + " times");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Hello Hello Hello Hello</div>
<div id="counter"></div>

You can just use this simple function countWords()
function countWords(str){return (str.match(/Hello/g) || []).length;;}
$('#counterValue').text( countWords($("#container").text()) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="container"> Hello and Hello but Hello is what I'm saying... last Hello!</div>
<div id="counter"> Hello: <span id="counterValue"></span> times </div>

Related

Making a "Guess the Color" game and can't figure out how to add the correct answer

I'm stumped on how to make the hex code displayed at the top one of the choices on the "board." This is what I've tried so far.
var colorCode = '#' + Math.random().toString(16).slice(2, 8);
hexCode.innerHTML = colorCode;
var divs = document.getElementsByTagName('div')
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);
}
.panel {
height: 100px;
width: 100px;
border: 2px solid yellow;
border-radius: 25%;
}
<header>
<h1>Guess the Color</h1>
</header>
<main>
<span id="hexCode"></span>
<div id="one" class="panel"></div>
<div id="two" class="panel"></div>
<div id="three" class="panel"></div>
<div id="four" class="panel"></div>
</main>
https://jsfiddle.net/magoo/6vdfcmnL/6/
Is not clear if you want to show the text above every panel or just make one of the panel below the title the correct one; By the way i edited the code to do both.
Try to edit the code like this to check if result as intended.
HTML part:
<header>
<h1>Guess the Color</h1>
</header>
<main>
<!-- question -->
<p id="hexCodeToGuess"></p>
<br>
<!-- one -->
<span id="oneHexCode" class="label"></span>
<div id="one" class="panel"></div>
<!-- two -->
<span id="twoHexCode" class="label"></span>
<div id="two" class="panel"></div>
<!-- three -->
<span id="threeHexCode" class="label"></span>
<div id="three" class="panel"></div>
<!-- four -->
<span id="fourHexCode" class="label"></span>
<div id="four" class="panel"></div>
</main>
Javscript part:
var colorCodeToGuess = '#' + Math.random().toString(16).slice(2, 8);
// set the first label with the question (the color code to guess)
hexCodeToGuess.innerHTML = colorCodeToGuess;
// list of panels
var panels = document.getElementsByClassName('panel');
// list of labels
var labels = document.getElementsByClassName('label');
// generate the position of the right answer panel (random to make it unpredictable)
var correctPanelIndex = getRandomInt(panels.length);
// cycle trough the divs
for (var i = 0; i < panels.length; i++) {
// set by default a random new color
var currentColorCode = '#' + Math.random().toString(16).slice(2, 8);
// the div is in the right answer position => override the current color with the colorCodeToGuess generate at the start (the problem of the previous code)
if(i == correctPanelIndex){
currentColorCode = colorCodeToGuess;
}
// set the color to the panel
panels[i].style.backgroundColor = currentColorCode;
// set the text on a label above the panel
labels[i].innerHTML = currentColorCode;
}
// an useful function to get a random integer passing it the numer of values possible
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
You will notice that one of the panels have the same code of the question of the first code written below the title.
I've also commented the code so you can remove the unwanted logic consciously.
Your question is a little vague but if i got it right you want to display the background color of one of your divs in hex format. The following code will do that. I have added comments on the code to explain what im doing.
//get your panels (using selector is better that using div)
var divs = document.querySelectorAll(".panel");
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundColor = '#' + Math.random().toString(16).slice(2, 8);
}
//get the current backgrounds of all panels and add them to an array in hex format
curruntColorsArr = [];
x = document.querySelectorAll(".panel");
for (i = 0; i < x.length; i++) {
//get background color
backgroundColors = x[i].style.backgroundColor
//convert to hex
function rgbToHex(rgb) {
return '#' + rgb.match(/[0-9|.]+/g).map((x, i) => i === 3 ? parseInt(255 * parseFloat(x)).toString(16) : parseInt(x).toString(16)).join('')
}
//push to array
curruntColorsArr.push(rgbToHex(backgroundColors));
}
//get random color from the array and set it to innerHTML
function random_item(items) {
return items[Math.floor(Math.random() * items.length)];
}
const hexCode = document.getElementById("hexCode")
hexCode.innerHTML = random_item(curruntColorsArr)
.panel {
height: 100px;
width: 100px;
border: 2px solid yellow;
border-radius: 25%;
}
<header>
<h1>Guess the Color</h1>
</header>
<main>
<span id="hexCode"></span>
<div id="one" class="panel"></div>
<div id="two" class="panel"></div>
<div id="three" class="panel"></div>
<div id="four" class="panel"></div>
</main>

Select next div with jquery?

//$(document).ready(function(){
$('.next').click(function(){
$('.box').fadeOut();
$('.box').next().fadeIn();
});
//});
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box" style="display:block;">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
I have a div .box, and the next button. I need to select the next div if i click the next button but only the first div not all. For example if i click next button while it shown box 1 then the next box that should be appear is 2 and so on. But now it shown 2 3 4. How to do this ?
you can get the first visible div using $(.box:visible) and then fadeIn next div to it. you can also add a check for last element, in which case you can fadeIn the first element. something like this:
//$(document).ready(function(){
$('.next').click(function(){
var visibleBox = $('.box:visible');
$(visibleBox).fadeOut();
if(!$(visibleBox).next('div').length)
$('.box').first().fadeIn();
else
$(visibleBox).next().fadeIn();
});
//});
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box" style="display:block;">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
It's showing 2 3 4 because you ares selecting ALL .box elements, i.e. 1 2 3 4
.next() of 1 = 2
.next() of 2 = 3
.next() of 3 = 4
.next() of 4 = nothing
You should find the box that is currently being shown, and then find it's next sibling.
// Filter by CSS rule
var $showing = $('.box').filter(function() {
return $(this).css('display') === 'block';
}).fadeOut();
// or using :visible
$showing = $('.box:visible').fadeOut();
$showing.next().fadeIn();
you can use another class to labeled, which div is on the display. for example, you add a class display. then you put that class, on the first box. when you click next, you can remove the class display from the current one, and move it into the next one.
HTML
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box display">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
CSS
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
.display{
display:block
}
JQuery
$('.next').click(function(){
var current = $('.box.display');
current.fadeOut().removeClass('display').next().fadeIn().addClass('display');
});
Demo : https://jsfiddle.net/dfaLnsmo/
If I understand your requirement this will work
$(document).ready(function(){
var i = 1;
$('.next').click(function(){
$('.box').fadeOut();
$('.box:nth-child(i)').fadeIn();
if(i >= $('.box').length)
i++;
else
i=1;
});
});
Try the following Jquery
var curr = 1;
$('.next').click(function(){
if(curr < $( ".box" ).length) {
$('.box').hide();
$( ".box" )[curr].style.display= "block";
curr += 1;
}
});
Here is the working jsfiddel : https://jsfiddle.net/Lv7yr820/1/

JQuery Show Hide Multiple Div Button

I need to develop a News page with 3 articles that can be hidden or showed one by one, by means of 2 buttons: "Show more news" and "Show less news"
Each article must be hidden/displayed by clicking the relevant button only once, starting from the last article (at the bottom page) to the first one (top of page). HTML:
<!-- Articles-->
<article id="art-1" class="row" >My first Art</article>
<article id="art-2" class="row art" >My second Art</article>
<article id="art-3" class="row art" >My last Art</article>
<!--Buttons-->
<button class="button-grey" id="show-less-news1">Show Less</button>
<button class="button-grey" id="show-less-news2">Show Less</button>
<button class="button-grey" id="show-less-news3">Show Less</button>
<button class="button-grey" id="show-more-news1">Show More</button>
<button class="button-grey" id="show-more-news2">Show More</button>
<button class="button-grey" id="show-more-news3">Show More</button>
I managed to do this with JQuery but the code is extremely verbose and I need 6 buttons instead of 2, but I believe there must be a simplier way to get the same result with a less complex code. This is the JQuery code:
$("#show-more-news1").css({display:'none'});
$("#show-more-news2").css({display:'none'});
$("#show-more-news3").css({display:'none'});
$("#show-less-news1").css({display:'none'});
$("#show-less-news2").css({display:'none'});
//function 1 less
$("#show-less-news3").click(function(){
$("#art-3").hide(400);
$("#show-less-news3").hide();
$("#show-more-news3").show();
$("#show-less-news2").show();
});
//function 2 less
$("#show-less-news2").click(function(){
$("#art-2").hide(400);
$("#show-less-news2").hide();
$("#show-more-news3").hide();
$("#show-less-news1").show();
$("#show-more-news2").show();
});
//function 3 more
$("#show-more-news3").click(function(){
$("#art-3").show(400);
$("#show-more-news3").hide();
$("#show-less-news2").hide();
$("#show-less-news3").show();
});
//function 3 less
$("#show-less-news1").click(function(){
$("#art-1").hide(400);
$("#show-less-news1").hide();
$("#show-more-news2").hide();
$("#show-more-news1").show();
});
//function 2 more
$("#show-more-news2").click(function(){
$("#art-2").show(400);
$("#show-more-news2").hide();
$("#show-less-news1").hide();
$("#show-less-news2").show();
$("#show-more-news3").show();
});
//function 1 more
$("#show-more-news1").click(function(){
$("#art-1").show(400);
$("#show-more-news1").hide();
$("#show-less-news1").show();
$("#show-more-news2").show();
});
Some CSS:
article {
position: realtive;
width: 100%;
height: 50px;
border: 1px solid red;
float:left;
background-color: yellow;
}
.button-grey {
display: block;
background-color: #cfcfcf;
width: 150px;
height: 30px;
float:right;
}
Here's a CodePen. Can someone help me to get the same result with a better code?
Thanks a lot!
Using your HTML with only two buttons and identical CSS
The following JS works for better for me:
Javascript:
var newsDepth = 3;
var maxNewsDepth = 3;
$('#show-more-news').hide();
$('#show-more-news').click( function () {
(newsDepth < maxNewsDepth ) && newsDepth++;
$('#art-' + newsDepth).show();
$('#show-less-news').show();
if (newsDepth == maxNewsDepth) $('#show-more-news').hide();
});
$('#show-less-news').click( function () {
( newsDepth > 1 ) && newsDepth--;
$('#art-' + (newsDepth + 1)).hide();
$('#show-more-news').show();
if (newsDepth == 1) $('#show-less-news').hide();
});
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Articles-->
<article id="art-1" class="row">My first Art</article>
<article id="art-2" class="row art">My second Art</article>
<article id="art-3" class="row art">My last Art</article>
<!--Buttons-->
<button class="button-grey" id="show-less-news">Show Less</button>
<button class="button-grey" id="show-more-news">Show More</button>
Here is a codepen for you
I've got a better version in this jsfiddle.
HTML:
<!-- Articles-->
<div id="articles">
<article id="art-1" class="row">My first Art</article>
<article id="art-2" class="row art">My second Art</article>
<article id="art-3" class="row art">My last Art</article>
</div>
<!--Buttons-->
<button class="button-grey" id="show-less">Show Less</button>
<button class="button-grey" id="show-more" style="display: none">Show More</button>
JS:
var allArticles = $('#articles article');
var visibleCount = 3;
$('#show-less').on('click', function() {
// no more articles to hide
if (visibleCount == 0) return;
// hide the previous one
$(allArticles[--visibleCount]).hide();
// Show the more button
$('#show-more').show();
// hide the less button
if (visibleCount == 0)
$('#show-less').hide();
});
$('#show-more').on('click', function() {
if (visibleCount == allArticles.length) return;
// show the next article
$(allArticles[visibleCount++]).show();
// Show the less button
$('#show-less').show();
// hide the more button
if (visibleCount == allArticles.length)
$('#show-more').hide();
});

javascript/jquery loop through divs and add next/prev buttons with click event [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
<div class="form">
<div class="step">This is step 1</div>
<div class="step">This is step 2</div>
<div class="step">This is step 3</div>
<div class="step">This is step 4</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
</div>
I know how to loop through the divs and get each div not a big deal, but I don't see the logic on how to loop through the divs and show only the first one, and then onclick next show the second one and so on (and same for previous).
Either vanilla JS or jQuery solutions are fine as solutions but what I'm really looking for is if any of you can explain me the exact logic behind it, because I can't really see it.
I can post some code that I've done but that's not the problem, but in how to program it logic
Thank you so much
Use :visible to find the DIV that's currently being shown, and .next() and .prev() to go forward and backward.
$("#nextBtn").click(function() {
var nextDiv = $(".step:visible").next(".step");
if (nextDiv.length == 0) { // wrap around to beginning
nextDiv = $(".step:first");
}
$(".step").hide();
nextDiv.show();
});
$("#prevBtn").click(function() {
var prevDiv = $(".step:visible").prev(".step");
if (prevDiv.length == 0) { // wrap around to end
prevDiv = $(".step:last");
}
$(".step").hide();
prevDiv.show();
});
.step {
display: none;
}
div.step:first-child {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<div class="step">This is step 1</div>
<div class="step">This is step 2</div>
<div class="step">This is step 3</div>
<div class="step">This is step 4</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
</div>
This is how I would try to solve this problem using few useful methods like next, prev, first and last + in conjunction with CSS active class to show current block.
var $steps = $('.step');
$('#nextBtn').click(function() {
var $next = $steps.filter('.active').removeClass('active').next('.step');
if (!$next.length) $next = $steps.first();
$next.addClass('active');
});
$('#prevBtn').click(function() {
var $prev = $steps.filter('.active').removeClass('active').prev('.step');
if (!$prev.length) $prev = $steps.last();
$prev.addClass('active');
});
.step {
margin-bottom: 10px;
padding: 10px;
background: #DDD;
display: none;
}
.step.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<div class="step active">This is step 1</div>
<div class="step">This is step 2</div>
<div class="step">This is step 3</div>
<div class="step">This is step 4</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
</div>
I had tried using the index based code. try it
var index = 0;
$(function () {
$('.step:not(:first)').hide();
$('#nextBtn').click(function () {
if (($('.step').length - 1) >= index) {
$('.step:eq(' + index + ')').hide();
index++;
$('.step:eq(' + index + ')').show();
}
});
$('#prevBtn').click(function () {
if (index != 0) {
$('.step:eq(' + index + ')').hide();
index--;
$('.step:eq(' + index + ')').show();
}
});
});

jquery: Count number of words in data attribute

I have some elements with data attribute containing some tags.
I need to count number of each element's tags.
like this:
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
and I want to do something like this:
$('div[data-tags]').each(function(){
var tags = $(this).data('tags'),
count = tags.split(' ').length;
$(this).css({marginLeft: (20 * count)});
});
But in this way the count will be 1 for both elements with data-tags="" and data-tags="foo" since the result for split would be like this:
"".split(' '); //[""]
"foo".split(' '); //["foo"]
and length of both of these is 1.
The only way I can think of is to add a condition and do the stuff if the split result was not [""]. But it doesn't look like a good idea. Or not the best at least.
I want to know if anyone has a better idea. thanks.
You can use regexp match instead of simple split:
$('div[data-tags]').css('marginLeft', function() {
var tags = $(this).data('tags');
return (tags.match(/\w+/g) || []).length * 20;
});
Demo: http://jsfiddle.net/dqfx0wun/2/
One way is to use Array.prototype.filter(), and String.prototype.trim(), to remove empty white-space-only array-elements:
$('div[data-tags]').each(function() {
var tags = $(this).data('tags'),
count = tags.split(' ').filter(function (word) {
return word.trim().length;
}).length;
$(this).css({
marginLeft: (20 * count)
});
});
div[data] {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
Or, alternatively, test for the length of the tags variable; zero is a falsey value:
$('div[data-tags]').each(function() {
var tags = $(this).data('tags'),
count = tags.split(' ').length;
$(this).css({
marginLeft: tags.length ? (20 * count) : 0
});
});
div[data] {
border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-tags="foo bar something else">
some text
</div>
<div data-tags="foo bar">
some text
</div>
<div data-tags="foo">
some text
</div>
<div data-tags="">
some text
</div>
References:
Array.prototype.filter().
String.prototype.trim().

Categories