How to alter the value of a div on each click - javascript

I have got a task to create a puzzle.I have 12 div.Each div contains different value up to 12.I have button like start now.I want to change my div value on each click of the start now button.
DEMO
<div id="container">
<div class="finder">
<div class="block1"> <div id="one"><h1>1</h1></div>
</div>
<div class="block1"> <div id="two"><h1>2</h1></div>
</div>
<div class="block1"> <div id="three"><h1>3</h1></div>
</div>
<div class="block1"> <div id="four"><h1>4</h1></div>
</div>
<div class="block1"> <div id="five"><h1>5</h1></div>
</div>
<div class="block1"> <div id="six"><h1>6</h1></div>
</div>
<div class="block1"> <div id="seven"><h1>7</h1></div>
</div>
<div class="block1"> <div id="eight"><h1>8</h1></div>
</div>
<div class="block1"> <div id="nine"><h1>9</h1></div>
</div>
<div class="block1"> <div id="ten"><h1>10</h1></div>
</div>
<div class="block1"> <div id="eleven"><h1>11</h1></div>
</div>
<div class="block1"> <div id="twelve"><h1>12</h1></div>
</div>
</div>
<div class="button">
<div id="startButton">
<button>Start</button>
</div>
</div>
</div>
js is
$(".finder").css('display','none');
$("#startButton").click(function () {
$(".finder").css('display','block');
});
var myDiv;
$(".block1 div").on('click', function(){myDiv = $(this)});
$(".block1 div").click(function () {
if(myDiv.text() < 12)
{
myDiv.text(parseInt(myDiv.text())+1);
}
if(myDiv.text() > 12)
{
myDiv.text(1);
myDiv.text(parseInt(myDiv.text())+1);
}
});
How can i change the values?

I have provided a solution below. One of the key takeaways you should get from it, is that when an event handler is used this will be assigned the element the event was trigger on within the bound function.
To Fill the boxes with random numbers use this code
$(function() {
//Array of values
var values = [1,2,3,4,5,6,7,8,9,10,11,12];
$( "input[type=submit], button" )
.button()
.click(function( event ) {
event.preventDefault();
});
$(".finder").css('display','none');
$("#startButton").click(function () {
var tmpValues = values.slice(); //copy array
$(".block1 div h1").each(function(){
var r = Math.floor(Math.random()*tmpValues.length);
//assign html to random array value that gets removed from array
$(this).html(tmpValues.splice(r,1));
});
$(".finder").css('display','block');
});
$(".block1 div").click(function () {
//Instead of setting myDiv use $(this) which will refer to the div
//We can grab the value of the H1 within the div using a scoped selector
var value = parseInt($("h1",this).html());
//Set the html of the clicked div
//When setting the html we must include new value in h1 to maintain style
//Ternary expression tidies up the logic, not sure why it sets to to 2 though?
$(this).html("<h1>" + ((value > 12) ? 2: value+1) + "</h1>");
});
});
Working Example http://jsfiddle.net/W55xc/3/

I didnt quite get the question, but I guess you want to generate random numbers for the div's, right? Use Math.random()
$(".block1 div").each(function() {
$(this).children('h1').text(Math.floor((Math.random() * 12) + 1)); // Generate a random number <-> [1, 12]
}

Related

Find the index of a div inside a container

I have a container with multiple divs and in each div I have a handler on which you can click.
The requirement is to return the index of the div in the container for further processing.
I've simplified the code for readability purposes.
The HTML:
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
The Javascript code I tried so far but I always get -1 as the index:
$(document).ready(function(){
$('.handler').click(function(e) {
let index = Array.prototype.indexOf.call($('.container'), $(this).parents('.block'));
console.log(index);
});
});
I also created a fiddle.
So what am I doing wrong here?
You can do the following,
$('.handler').click(function(e) {
var el = e.target;
console.log([].indexOf.call(el.parentNode.parentNode.children, el.parentNode));
});
However if you want to know what was wrong in your code,
Array.prototype.indexOf.call($('.container')[0].children, $(this).parents('.block')[0])
This part should fix the problem in your code. You have been doing it all right, but for the parameter of indexOf we needed the children array of .container and clicked element.
You were passing the container element and current clicked element as an array. That is Array.prototype.indexOf.call('[Container Element]', ['current clicked div']) Which is not right. You should pass something like this,
Array.prototype.indexOf.call('[children, children, children...]', 'current clicked div element').
It was happening because the $('.container') returns an array with the element having a class name .container. But we needed all the children array of the element that contains container class.
And $(this).parents('.block') returns an array with the matching elements even if it is only one.
You can access the index using the index method on parent element of selection.
$(document).ready(function(){
$('.handler').click(function(e) {
console.log($(this).parent().index())
});
});
You can do that like this. Find the index of the closest element of the clicked element, which is also a direct child of .handler. To find index, use index().
$(document).ready(function() {
$('.handler').click(function(e) {
let index = $(this).closest('.block').index()
console.log(index);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
<div class="block">
<div class="handler">
Click
</div>
</div>
</div>
You're checking at the wrong level of nesting in your HTML. I believe what you're trying to do is check from one level higher, at ".container" and get the index of the ".block" element that was clicked.
This code works in your Fiddle:
$(document).ready(function(){
$('.handler').click(function(e) {
const p = e.target.parentElement.parentElement;
const index = Array.prototype.indexOf.call(p.children, e.target.parentElement);
console.log(p.className) // "container"
console.log(index)
});
});
This can be done simply using delegate in jQuery.
I modify your JSFiddle code.
$(".container").delegate('.block', 'click', function () {
console.log( $(this).index() );
})
u can use a id
<div class="container">
<div class="block">
<div id='0' class="handler">
Click
</div>
</div>
<div class="block">
<div id='1' class="handler">
Click
</div>
</div>
<div class="block">
<div id='2' class="handler">
Click
</div>
</div>
<div class="block">
<div id='3' class="handler">
Click
</div>
</div>
</div>
$(document).ready(function(){
$('.handler').click(function(e) {
let index = this.id
console.log(index);
});
});
https://jsfiddle.net/vhrt596x/2/

How to get number of div left after deleting?

In my HTML there are eight div. I was able to get the number of the div using jQuery and insert it into the .num div element.
However when I delete one of the div by clicking the delete button, the number of divs in the span retrieved through jQuery won't update to the current number of divs remaining. It will still show 8.
How can I get the current number of div elements left in the DOM immediately after clicking the button?
setTimeout(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
```
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
The problem is because you're using setTimeout(), which only runs once after the specified delay.
For the pattern you're using to work you need to use setInterval() instead, which will run repeatedly at the set delay:
setInterval(() => {
if ($(".delete div").length > 0) {
$(".num span").html($(".delete div").length);
}
}, 100);
$("button").click(function() {
$(".delete div:last-child").remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>
However, using a timer for this is not ideal. As the number of div elements is only affected when the button is clicked, just update the .num span element in that event handler:
var $span = $(".num span").html($(".delete div").length);
$("button").click(function() {
$(".delete div:last-child").remove();
$span.html($(".delete div").length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="delete">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
<div class="div4">4</div>
<div class="div5">5</div>
<div class="div6">6</div>
<div class="div7">7</div>
<div class="div8">8</div>
</div>
<div class="num">Number of div: <span>0</span></div><br>
<button>delete</button>

JS Value returning form all divs

I am trying to get first letter of firstname and lastname from a div and paste it in another div but it is pasting the same value in all divs and not taking unique value from each div.
Working Fiddle: https://jsfiddle.net/bv7w8dxg/1/
Issue Fiddle: https://jsfiddle.net/bv7w8dxg/
var takword = $('.nameholder').text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder').text(text);
Markup
`
John Doe
<div class="main-holder">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="main-holder">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>`
You are using class selectors, which selects all elements with the given class name. That's why you have all the elements set with same value
You need to wrap your elements then process each row independently
I updated your code snippet to demonstrate this:
$('.row').each(function() {
var takword = $('.nameholder', this).text().split(' ');
var text = '';
$.each(takword, function () {
text += this.substring(0, 1);
});
$('.avatarholder', this).text(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="nameholder">John Doe</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Kyle Davis</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Seim Seiy</div>
<div class="avatarholder"></div>
</div>
<div class="row">
<div class="nameholder">Momma Boy</div>
<div class="avatarholder"></div>
</div>

How to get previous element from click target?

Hello I have this html code:
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>
When I click on img with id exit using this code
$('body').on('click','#exit',function(e){
})
I need to get the text of the <b>behind it which would be "this"
I have tried this but it does not work:
$('body').on('click','#exit',function(e){
$q = $(e.target).prev('b')
var word = $q.text()
)}
It only gives me the that I clicked from the beginning
try this:
$('body').on('click','#exit',function(e){
var this_b = $(this).parent().prev().children(0).html();// get the text
alert(this_b);
});
You can use $(this).closest('.row').find('b'):
$('#exit').click(function(e){
$q = $(this).closest('.row').find('b');
var word = $q.text();
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>
You need to select the parent of the clicked img to get the the .col-2, and then get the col-2's prev() to get to the .col-10, and then you can access its children() to get the children (the single <b>). Also, there's no need for e.target if you use this:
$('body').on('click', '#exit', function() {
$q = $(this).parent().prev().children();
var word = $q.text()
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit" />
</div>
</div>
Try this
$('body').on('click','#exit',function(e){
var word = $(this).closest('.newrow').find('b').text();
});

Toggle multiple classes

I'm stuck with a menu I'd love to add to my website.
I have branched my work in:
Commercial
Fashion
Music
Portrait
So I have a menu like this one above.
When I click on one section, let's say "Commercial" I want all the others to be display:none.
Have a look at this FIDDLE: http://jsfiddle.net/bfevLsj2/8/
$(document).ready(function() {
$("#commercial").click(function() {
$(".commercial").toggleClass("show");
$(".fashion").toggleClass("hid");
$(".music").toggleClass("hid");
$(".portrait").toggleClass("hid");
});
});
You need siblings() width jquery
Description: Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
$("[id]").click(function(){ //onclick on element with ID
var selected = $(this).attr("id"); // save the value of that ID
$("."+ selected).show().siblings("[class]").hide()//find the class with the same value as class and show it then find all siblings class and hide them
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="commercial">Commercial</div>
<div id="fashion">Fashion</div>
<div id="music">Music</div>
<div id="portrait">Portrait</div><br />
<div class="commercial">C</div>
<div class="fashion">F</div>
<div class="music">M</div>
<div class="portrait">P</div>
BUT a better approach would be to use data-*
$("[data-tab]").click(function(){
var current = $(this).attr("data-tab");
$("[data-content="+ current +"]").show().siblings("[data-content]").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
AGAIN it is better to use pure javascript
function runClick (event) {
var current = this.getAttribute("data-tab");
for( var content = 0; content < dataContent.length; content++) {
dataContent[content].style.display = "none"
}
document.querySelector("[data-content="+ current + "]").style.display = "block"
}
var dataTabs = document.querySelectorAll("div[data-tab]"),
dataContent = document.querySelectorAll("div[data-content]");
for(var tab = 0; tab < dataTabs.length; tab++){
dataTabs[tab].addEventListener("click", runClick , false);
}
<div data-tab="commercial">Commercial</div>
<div data-tab="fashion">Fashion</div>
<div data-tab="music">Music</div>
<div data-tab="portrait">Portrait</div><br />
<div data-content="commercial">C</div>
<div data-content="fashion">F</div>
<div data-content="music">M</div>
<div data-content="portrait">P</div>
HTML:
<div id="commercial" class="menuItem">Commercial</div>
<div id="fashion" class="menuItem">Fashion</div>
<div id="music" class="menuItem">Music</div>
<div id="portrait" class="menuItem">Portrait</div><br />
<div class="commercial content">C</div>
<div class="fashion content">F</div>
<div class="music content">M</div>
<div class="portrait content">P</div>
JavaScript:
$(document).ready(function(){
$(".menuItem").click(function(){
var id = this.id;
$('.content').removeClass('show').addClass('hid');
$('.'+id).addClass('show').removeClass('hid');
});
});
CSS:
.hid {
display:none;
}
.show {
display:block;
}
Fiddle
Have a look at this fiddle, think it's what you want
Essentially you can use .toggle() to traverse and show/hide according to whether it's the one you want to show.
$(function(){
// find all the links that you can click
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId));
});
});
});
And the HTML:
<div id="commercial" class="clickable">Commercial</div>
<div id="fashion" class="clickable">Fashion</div>
<div id="music" class="clickable">Music</div>
<div id="portrait" class="clickable">Portrait</div>
<br />
<div class="commercial section">C</div>
<div class="fashion section">F</div>
<div class="music section">M</div>
<div class="portrait section">P</div>
HTH
Edited to add an "ALL" link in this fiddle
$("div.clickable a").click(function(e) {
// when they're clicked, find the identifier of
// the tab/div you want shown
var clickedId = $(e.target).parent("div").attr("id");
// traverse all of the divs and show/hide according
// to whether it's the tab you want
$("div.section").each(function(index, div) {
$(div).toggle($(div).hasClass(clickedId) || clickedId=="ALL");
});
});
After adding this to the list of clickable divs:
<div id="ALL" class="clickable">
ALL
</div>
Your could that more easy like:
<div class="link" id="commercial">Commercial</div>
<div class="link" id="fashion">Fashion</div>
<div class="link" id="music">Music</div>
<div class="link" id="portrait">Portrait</div><br />
<div class="commercial elem">C</div>
<div class="fashion elem">F</div>
<div class="music elem">M</div>
<div class="portrait elem">P</div>
<script type="text/javascript">
$(document).ready(function(){
$(".link").click(function(){
var id = $(this).attr('id');
$('.elem').hide();
$('.' + id).show();
});
});
</script>

Categories

Resources