When a button is clicked, its background-color does not become yellow as intended nor does the previously clicked button's background-color revert to red. My goal is to change the buttons' colors when they are clicked by changing their classes. When the buttons' classes are changed they do not change color. The purpose of testFunction() is updating the color of the buttons. The purpose of testFunction2() is adding an onclick function to the buttons.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<style>
.button {
background-color: red;
}
.c {
background-color: yellow;
}
</style>
<body>
<table>
<tr>
<td>test1</td>
</tr>
<tr>
<td id="test1">
<button class="c">0</button>
<button class="">1</button>
<button class="">2</button>
<button class="">3</button>
</td>
</tr>
<tr>
<td>test2</td>
</tr>
<tr>
<td id="test2">
<button class="c">0</button>
<button>1</button>
<button>2</button>
<button>3</button>
</td>
</tr>
</table>
<script>
var lastClick1 = 0;
var lastClick2 = 0;
//alert('js');
function testFunction(c, n) {
// alert('tf');
if (c == 0) {
// alert('s=0');
if (lastClick1 != n) {
var a = document.getElementById("test1").children;
a[lastClick1].class = '';
a[n].class = 'c';
alert('n: ' + n + ' class: ' + a[n].class);
alert('lastclick:' + lastClick1 + ' class: ' + a[lastClick1].class);
lastClick1 = n;
}
} else {
// alert('else');
if (lastClick2 != n) {
var b = document.getElementById("test2").children;
b[lastClick2].class = '';
b[n].class = 'c';
alert('n: ' + n + ' class: ' + b[n].class);
alert('lastclick:' + lastClick2 + ' class: ' + b[lastClick2].class);
lastClick2 = n;
}
}
}
function testFunction2() {
//alert('tf2');
var t1 = document.getElementById("test1").children;
var t2 = document.getElementById("test2").children;
//alert(t1);
for (var i = 0; i < 6; i++) {
t1[i].onclick = function() {
testFunction(0, parseInt(this.innerText));
};
t2[i].onclick = function() {
testFunction(1, parseInt(this.innerText));
};
}
}
testFunction2();
</script>
</body>
</html>
Add to jQuery
link
CSS
.button {
background-color: red;
}
.c {
background-color: yellow;
}
.r{
background-color: red;
}
Jquery
$(function(){
$('button').on('click', function () {
$(this).parent('td').children('.c').removeClass('c').addClass('r');
$(this).addClass('c');
})
});
Related
I have a table and I have one 1 cell that I can't fix. What I want is to have a background colour blue and when I click the
<p> 2 click me </p>
I want to make this background cell green. I take only the code for this specific cell, what I have done and it doesn't work as I want..
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
var x = document.getElementById('colour');
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
#click{
background-color: blue;
padding: 1rem;
width : 50%;
height: 50px;
margin: auto;
}
<tr>
<td id="click">
<div id="colour" onclick="myFunction()">
<p>2 click me<p>
</div>
</td>
</tr>
is this what you want? I think you just need to assign a variable to the element colour and then use it to make your changes
function myFunction() {
const x = document.getElementById("colour");
const y = document.getElementById("click");
x.innerHTML = "YOU CLICKED ME!";
if (y.style.backgroundColor === 'green') {
y.style.backgroundColor = 'blue';
} else {
y.style.backgroundColor = 'green';
}
}
#click {
background-color: blue;
padding: 1rem;
width: 50%;
height: 50px;
margin: auto;
}
<table>
<tr>
<td id = "click">
<div id="colour" onclick="myFunction()">
<p>2 click me</p>
</div>
</td>
</tr>
</table>
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
var x = document.getElementById('colour');
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
**</script>**
You forgot to close with the script tag I think, right?
Because for me closing with the tag it works
#click{
background-color:blue;
padding:1rem;
width : 50%;
height:50px;
margin:auto;
}
<body>
<tr>
<td id="click" > <div id="colour" onclick="myFunction()"><p>2 click me<p></div></td>
</tr>
</body>
<script type="text/javascript">
var x = document.getElementById('colour');
function myFunction() {
document.getElementById("colour").innerHTML = "YOU CLICKED ME!";
}
x.addEventListener('click', function()
{
if (x.style.backgroundColor === 'green') {
x.style.backgroundColor = 'blue';
} else {
x.style.backgroundColor = 'green';
}
});
</script>
With this it should work!
In my code, each class will be toggled by clicking them.
I would like to understand the data,class-index, in my code,class-index is changed and class will be changed aligned with this.
But when I look at developer tool, class-index dosen't seems to be changed.
<td class="classC" data-class-index="0">Value 1</td>
<td class="classB" data-class-index="0">Value 1</td>
Considering this, I add undo button,it works as a reverse of toggle,but it didn't work well.
How can I fix it?
$(function(){
var classArray = ['classA','classB','classC'];
var arrLen = classArray.length;
$("#our_calendar td").click(function() {
var classIndex = $(this).data('class-index');
$(this).removeClass(classArray[classIndex]);
if(classIndex < (arrLen-1)) {
classIndex++;
} else {
//reset class index
classIndex = 0;
}
$(this).addClass(classArray[classIndex]);
$(this).data('class-index',classIndex);
});
$("#undo").on('click',function() {
var classIndex = $(this).data('class-index');
$(this).removeClass(classArray[classIndex]);
classIndex--;
$(this).addClass(classArray[classIndex]);
$(this).data('class-index',classIndex);
})
});
.classA {
background-color: aqua;
}
.classB {
background-color: yellow;
}
.classC {
background-color: red;
}
td {
transition-duration:0.4s ;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="our_calendar">
<tr><td class="classA" data-class-index="0">Value 1</td></tr>
</table>
<button id="undo">undo</button>
With regard to the DOM not being updated, this is expected behaviour as the data() method only updates jQuery's internal cache of data attributes. It does not update the data attributes held in the relevant elements in the DOM.
With regard to your issue, the main problem is because you're using this within the #undo click handler. That will refer to the clicked button, not the td with the class on it. You just need to target the right element.
Also note that the classIndex logic can be simplified by using the modulo operator. Try this:
$(function() {
let classArray = ['classA', 'classB', 'classC'];
let arrLen = classArray.length;
let $td = $("#our_calendar td");
$td.click(function() {
let classIndex = $td.data('class-index');
$td.removeClass(classArray[classIndex]);
classIndex = ++classIndex % classArray.length;
$td.addClass(classArray[classIndex]);
$td.data('class-index', classIndex);
});
$("#undo").on('click', function() {
let classIndex = $td.data('class-index');
$td.removeClass(classArray[classIndex]);
classIndex = (--classIndex + classArray.length) % classArray.length;
$td.addClass(classArray[classIndex]);
$td.data('class-index', classIndex);
});
});
.classA { background-color: aqua; }
.classB { background-color: yellow; }
.classC { background-color: red; }
td { transition-duration: 0.4s; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="our_calendar">
<tr>
<td class="classA" data-class-index="0">Value 1</td>
</tr>
</table>
<button id="undo">undo</button>
I've been working on a simple code that would detect how many clicks an item has received and it would put it on the top of the list, the problem is, I can only replace the first item once, if I clicked on it again it's doesn't add up the number of clicks inside of the items. Why is this?
My code: (Ctrl + Shift + I) and inspect the items to see them change
$(function() {
$('.watchMe > .item').attr({
"influence": "0"
});
});
$('.watchMe > .item').mousedown(function() {
$(this).attr({
"influence": parseInt($(this).attr("influence"), 10) + 1
});
});
$(document).on('mouseup', function(e) {
rearrangeEm();
});
function rearrangeEm() {
var tempArray = [];
$('.watchMe > .item').each(function() {
tempArray.push([this, parseInt($(this).attr("influence"), 10)]);
console.log(this);
});
for (var i = 0; i < tempArray.length; i++) {
for (var j = i + 1; j < tempArray.length; j++) {
var temp;
if (tempArray[i][1] < tempArray[j][1]) {
temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
$('.watchMe').empty();
for (i = 0; i < tempArray.length; i++) {
$('.watchMe').append(tempArray[i][0]);
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>smartSystem</title>
<style>
.item {
height: 100px;
border: 1px solid #c3c3c3;
}
</style>
</head>
<body>
<div class="watchMe">
<div class="item">a</div>
<div class="item">b</div>
<div class="item">c</div>
</div>
</body>
</html>
The issue is because you're removing the original .item elements which have the mousedown event bound to them, so you need to use a delegated event handler. Try this:
$('.watchMe').on('mousedown', '> .item', function() {
$(this).attr({
"influence": parseInt($(this).attr("influence"), 10) + 1
});
});
Note however, that you can both improve and shorten your logic using data() attributes (as opposed to a custom attribute which will make your HTML code invalid) and the sort() method. Try this:
$(function() {
$('.watchMe').on('mousedown', '> .item', function() {
$(this).data('influence', ($(this).data('influence') || 0) + 1);
});
$(document).on('mouseup', function(e) {
rearrangeEm();
});
});
function rearrangeEm() {
$('.watchMe > .item').sort(function(a, b) {
var aInf = $(a).data('influence') || 0, bInf = $(b).data('influence') || 0;
return aInf < bInf ? 1 : aInf > bInf ? -1 : 0;
}).appendTo('.watchMe');
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title>smartSystem</title>
<style>
.item {
height: 100px;
border: 1px solid #c3c3c3;
}
</style>
</head>
<body>
<div class="watchMe">
<div class="item">a</div>
<div class="item">b</div>
<div class="item">c</div>
</div>
</body>
</html>
I am using a $.getJSON function to return JSON from an API of employee salaries. For each entry, I have a counter that goes up for each employee returned. I added a list that allows the user to choose the department the employee works in as a variable to check when the function is wrong. When the check function runs for all employees, it works as expected returning 1000 employees. However, when I add in the if statement, it does add any employees to the employee counter.
I am logging the selected department to the console and can see the department is correctly selected. I think put in a string of "Department of Police" to use in the function and it return 186 employees. If I use the variable checkedValue which shows in the console the same value I would expect the same function to return 186 employees but it does not. The value is held in the JSON object as a string so I'm not sure if the wrong data would be the problem.
What am I doing wrong?
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<body>
<div id="page">
<div id="content">
<div id="button-area">
<button id="check">Check the radio button</button>
<button id="action">Do Action</button>
</div>
<div id="checks">
</div>
<div>
<ul id="list"></ul>
</div>
</div>
</div>
</body>
CSS:
body {
font-family: 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;
height: 100%;
width: 100%;
margin: 0 !important;
padding: 0 !important;
}
#page {
width: 80%;
margin: 0 auto;
border: 1px solid black;
box-shadow: 3px 3px 5px 2px black;
}
#content {
margin: 10px;
}
#button-area {
padding-top: 50px;
width: 100%;
height: 100px;
margin: 0 auto;
text-align: center;
}
JavaScript:
var url;
var myNewObject;
var myObject;
var departmentArray;
var cleanedDepartmentArray;
var checkedValue;
var budget = 0;
var employees = 0;
function setTheList() {
$.getJSON(url, function(data) {
myObject = data;
for (var i = 0; i < myObject.length; i++) {
departmentArray.push(myObject[i].department_name);
};
$.each(departmentArray, function(i, el) {
if ($.inArray(el, cleanedDepartmentArray) === -1) {
cleanedDepartmentArray.push(el);
}
});
for (var i = 0; i < cleanedDepartmentArray.length; i++) {
$('#list').html("");
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
};
});
};
$(document).ready(function() {
console.log("Initialized with " + employees + " employees and " + budget +
" budget.");
url = 'https://data.montgomerycountymd.gov/resource/54rh-89p8.json';
myObject;
myNewObject;
departmentArray = [];
cleanedDepartmentArray = [];
//set the list
setTheList();
//get checked radio button value
function getCheckedValue() {
checkedValue = "";
checkedValue = $("input[name=department]:checked").val();
console.log(checkedValue);
};
//call geojson
function getData(checkedValue) {
getCheckedValue();
$.getJSON(url, function(data) {
myNewObject = data;
console.log("my new object: ", myNewObject)
for (i = 0; i < data.length; i++) {
if (data[i].department_name === checkedValue) {
employees++;
};
};
console.log(checkedValue);
console.log(employees)
});
};
$('#check').on('click', function() {
getCheckedValue();
});
$('#action').on('click', function() {
getData(checkedValue);
});
});
There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Seeing if I can highlight this any clearer for you:
There's a space after the value of the value attribute in the line below. I assume this shouldn't be here?
$('#checks').append("<li><input type='radio' name='department' value='" +
cleanedDepartmentArray[i] + " '>" + cleanedDepartmentArray[i] +
"</li>");
Just to see if I can highlight it any better:
cleanedDepartmentArray[i] + " ' <<< this bit
I'm trying to fix my jQuery code. I want 'add content' button in the last div only. If a div is removed, the button stays in the last div. Suggestions please.
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".hide_button").remove();
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br> <button class="addcontent hide_button' + i + '">Add content</button></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
$(".question").append('<button class="addcontent hide_button">Add content</button>').show('slow');
}
});
});
HTML:
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Try this:
Move your button out of your div:
HTML:
<div class="question">
</div>
<button class="addcontent hide_button">Add content</button>
JS:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
JSFIDDLE: http://jsfiddle.net/ghorg12110/a7L3cn1a/1/
Here is the updated/working code.
HTML:
<div>
<div class="question"></div>
<button class="addcontent">Add content</button>
</div>
JavaScript:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) {
$(".question").html('');
}
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question'+i+'">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
A little hard to see what you have in mind, but I would have the button in all the divs and use CSS to show or hide the button.
div button { display: none; }
div:last-of-type button { display: inline; }
It's more efficient if you use CSS to overlap that property at the end and you will conserve the same element with the necessity of adding and removing it
html:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="content" class="content"></div>
<button class="addcontent hide_button">Add content</button>
</body>
</html>
css:
.new-question {
background-color: green;
width: 300px;
height: auto;
position: relative;
margin:0;
}
.deleteButton {
background-color: red;
width: 50px;
height: 50px;
margin-left: 100%;
position: relative;
}
.addcontent{
z-index: 1;
top:-25px;
left:200px;
position:relative;
}
.content{
min-height:30px;
}
js:
$(function (){
var i = 1,
contentQuestion = $('<div class="new-question"></div>'),
remove = $('<div class="deleteButton">Remove</div>').appendTo(contentQuestion),
content = $('#content');
$('.addcontent').on('click', function () {
content.append(contentQuestion.clone().append('<b>Question ' + i + '</b><br> This is div text'));
i += 1;
});
content.on('click', '.deleteButton', function () {
$(this.parentNode).remove();
});
});
jsbin:
http://jsbin.com/gequveroba/1/edit?html,css,js,output