i want to create a star rating in JavaScript. - javascript

I want to create a star rating in JavaScript in which default is 5 i will go down to 1 but i didn't understand how to fill up from 1 to 5.
Here is my code :-
$(".star").click(function(){
var starselect = $(this).attr("id");
for( var j = 5 ; j>starselect ; j--)
{
$("#"+j).removeClass("starchecked");
}
if( j < starselect+1 ){
$("#"+j).addClass("starchecked");
}
$(".review-star").attr("data-rating",starselect);
});

Per my comment, I would do this using css, but if you need to use js, then I would use a mixture of nextAll, prevAll and andSelf - see comments in code
var $stars = $(".star")
$stars.click(function() {
var $star = $(this);
if ($star.hasClass('checked')) {
// if current clicked star is checked
if ($star.next().hasClass('checked')) {
// check if next star is also checked
$star.nextAll().removeClass('checked'); // if next is then disable all following
} else {
$star.nextAll().andSelf().removeClass('checked'); // if not then disable self and all after (shouldn't need all after, but just in case)
}
$star.prevAll().addClass('checked'); // check all before
// if you just want to remove all stars on click of an already checked box, remove the above 2 lines and just ue the below:
// $stars.removeClass('checked');
} else {
$star.nextAll().removeClass('checked'); // remove checked from all following the clicked
$star.prevAll().andSelf().addClass('checked'); // add checked to this and all previous
}
var starselect = $stars.index($star) + 1; // get current star rating
$(".review-star").attr("data-rating", starselect);
console.log(starselect);
});
.star {
border: 1px solid black;
width: 20px;
height: 20px;
display: inline-block;
}
.checked {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="star">1</span>
<span class="star">2</span>
<span class="star">3</span>
<span class="star">4</span>
<span class="star">5</span>

Related

How to toggle a button to an active state using vanilla JS?

I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.
I have the following code to create the buttons:
var button;
createButtons();
function createButtons() {
for (i = 0; i < 20; i++) {
//creates a new button
button = document.createElement('Button');
//sets correct button number and button text
var index = i + 1;
var text = document.createTextNode('Button ' + index);
button.appendChild(text);
button.className += "button";
button.className += " default-button";
document.body.appendChild(button);
}
}
Modern browsers support the classList API now.
In order to use the classList API, try adding the following to your code:
var buttons = document.getElementsByClassName('button')
Array.prototype.forEach.call(buttons, function (button) {
button.addEventListener('click', function (event) {
button.classList.toggle('button-active')
})
})
If you want to only turn the active state on, switch the toggle method of classList to add. Read more on classList.
Breakdown of code example:
First I select all .button elements and store them in a NodeList data type.
Then I call array's forEach function (another way of doing the same would be [].forEach.call() but that creates new Array instance every time it runs). I add an event listener for click event upon which I toggle a new class name.
For a direct CSS manipulation, you can use button.style.color = 'red' - but I discourage you from this approach to keep your code maintainable.
Note from Phil (in the comments to this answer):
You can use NodeList.prototype.forEach() which shortens the line into buttons.forEach(function (button) {. Bear in mind that Internet Explorer does not support this.
CSS alternative without JavaScript:
input[type=checkbox] { display: none; }
input[type=checkbox] + label { background-color: cyan; }
input[type=checkbox]:checked + label { background-color: red; }
<input type=checkbox id=t1><label for=t1> Toggle 1 </label><br>
<input type=checkbox id=t2><label for=t2> Toggle 2 </label><br>
<input type=checkbox id=t3><label for=t3> Toggle 3 </label><br>
<input type=checkbox id=t4><label for=t4> Toggle 4 </label><br>
<input type=checkbox id=t5><label for=t5> Toggle 5 </label><br>
Assuming you only want one button "active" at a time, I would just use the CSS :focus / :active pseudo-class. For example
for (let i = 1; i <= 20; i++) {
let btn = document.createElement('button')
btn.textContent = `Button ${i}`
btn.classList.add('button', 'default-button')
document.body.appendChild(btn)
}
.button {
background-color: blue;
color: white;
font-weight: bold;
}
.button:active, .button:focus {
background-color: red;
}
You can use button.onclick = function(){ // do things here. };
I have included the code in a snippet below. Good luck.
var button;
createButtons();
function createButtons() {
for (i = 0; i < 20; i++) {
//creates a new button
button = document.createElement('Button');
//sets correct button number and button text
var index = i + 1;
var text = document.createTextNode('Button ' + index);
button.appendChild(text);
button.className += "button";
button.className += " default-button";
// --------------------------------------------------------
// on click check if it contains the class for the color
// and toggle it on or off.
button.onclick = function() {
if (this.classList.contains("enableColor")) {
this.classList.remove('enableColor');
} else {
this.classList.add("enableColor");
}
}
// --------------------------------------------------------
document.body.appendChild(button);
}
}
.enableColor {
background: red;
color: white;
}
.focus(), but most browsers actually block button click type behavior for security purposes. What you can do is set the button elements disabled = true attribute then when you get whatever action you are looking for toggle that attribute to disabled = false.
Here's a snippet you could adapt:
// enables submit button iif inputs meet validation contraints
function attachKeyupListenerToInputElements(){
var inputs = doc.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keyup", keyupHandler);
}
function keyupHandler() {
if(this.value === ''){
this.setCustomValidity('Required Field');
} else {
this.setCustomValidity('');
}
//for dialog inputs
if(doc.querySelector(".mdc-dialog").classList.contains("mdc-dialog--open")){
//dialog is open
var thisSection = this.parentElement.parentElement;
var theseInputs = thisSection.querySelectorAll("input");
var inputsFull = true;
for (var i = 0; i < theseInputs.length; i++) {
if(!theseInputs[i].checkValidity()){
inputsFull = false;
}
}
if(inputsFull){
doc.getElementById("dialog-accept-button").disabled = false;
}
}
}
}

Getting value from followup fieldset when prior one is clicked

I am able to dynamically create fieldsets on button click. Let say first time I click button it creates Definition 1 then Definition 2 then Definition 3 etc.
Each fieldset has X mark to remove the dynamically created fieldset if one was created by accident.
What I am trying to do is for example Definition 2 fieldset was deleted then Definition 3 one should say Definition 2.
What I need to know is when I click X mark in one fieldset, grab the value of the legend from the next fieldset and change it to the value of the one deleted.
Here is what my dynamic call looks like:
if($(".addDef").length > 0){
i++;
}else{
i = 2;
}
$(".definitionBlock").append("<fieldset><legend class='addDef'>Definition #"+ i +"</legend><div class='removeDef'><span>✖</span></div>
</fieldset>");
Thanks!
You can use .text(function(index, text){}) to replace digit portion of .textContent with index of element within collection
var n = 2;
$(".addDefBtn").on("click", function() {
if (!$(".addDef").length) {
n = 2;
}
$(".mvnDefinitionBlock").append("<fieldset class='addDef'><legend class='addDefTitle'>Definition #" + n++ + "</legend><div class='removeDef'><span>✖click</span></div></fieldset>");
});
$('body').on('click', '.removeDef', function() {
$(this).closest('fieldset').remove();
n = 2;
$(".addDef legend").text(function(index, text) {
return text.replace(/\d+/, n++);
});
});
.removeDef {
float: right;
margin-top: -20px;
font-size: 13px;
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Add New Definition
<div class="mvnDefinitionBlock"></div>

A loop within a loop - Javascript

I have a problem with a loop inside a loop.
By selecting the number and clicking the "Generate boxes" button it generates boxes with numbers from 1 to 49.
If you click the first time everything works fine.
But if you add more boxes it once again adds those 49 numbers to the already existing boxes. That's the problem. I only want to generate new boxes with numbers from 1 to 49.
This is the code:
function kasterl() {
$(".plunder").click(function() {
var wert = $( "#wieviel option:selected").text();
MyInt = parseInt(wert);
createKaesten(MyInt);
});
}
function createKaesten(zahl) {
var gesamt = $(".kasten").length+1;
var numberOf = $(".kasten").length;
for(var i=1; i<=zahl; i++) {
$(".rahmen").append("<div class='kasten nr"+ gesamt +"'><ul></ul></div>");
}
for(var n=1; n<=49; n++) {
$(".kasten ul").append("<li class='nummer'>" + n + "</li>");
}
}
And here you can test it: link for testing
As you have found, $(".kasten ul").append(...) will append to all elements that matched the ".kasten ul" selector.
You said you had a problem with a "loop within a loop", but your current code doesn't in fact nest the loops. Following is a solution that actually does nest the loops:
function createKaesten(zahl) {
var gesamt = $(".kasten").length + 1;
var numberOf = $(".kasten").length;
var newUL;
for (var i = 1; i <= zahl; i++) {
newUL = $("<ul></ul>");
for (var n = 1; n <= 5; n++) {
newUL.append("<li class='nummer'>" + n + "</li>");
}
$("<div class='kasten nr" + gesamt + "'></div>").append(newUL).appendTo(".rahmen");
}
}
$("button").click(function() {
createKaesten(3);
});
li { display: inline-block; padding: 0 10px; }
.kasten { border: thin black solid; margin: 2px; padding: 0px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Test</button>
<div class="rahmen"></div>
The outer loop creates a new, empty UL, then the inner loop appends the new LI items to that UL, then we create a DIV, append the new UL to it, then append the DIV to the .rahmen" container.
(Note that for demo purposes each click of the button only adds 3 x 5 items, rather than something x 49 items, and I've styled the LIs to go across the page horizontally so that it's easier to see what's happening. Click "Run code snippet" to try it out.)
Note in the code that you use the function $().append()
Appending does just that - it appends new content to the end of existing content. Append will be executed every time you click generate.
Edit: I added a codepen to illustrate this. Hit each button multiple times to see the difference.

How to leave one active button in the JavaScript?

I am beginner.
I have four buttons and I want to leave one active button every time with expression operator (if). One button must have active every time .
I tried to do it something like that. I am open to your ideas, if you can do without (if) .Help me!
var count = 4;
var flag = true;
function select(currentColor, changeColor){
if(count > 1 && flag === true){
var currentElement = angular.element(document.getElementsByClassName(currentColor));
currentElement.toggleClass(changeColor);
count--;
console.log(count);
console.log('From minus: ' + count);
}else{
flag = false;
}
if(count < 4 && flag === false) {
var currentElement = angular.element(document.getElementsByClassName(currentColor));
currentElement.toggleClass(changeColor);
count++;
console.log(count);
console.log('From plus: ' + count);
}else{
flag = true;
}
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<style>
.changeColor{
color: red !important;
}
.first{
color: #07888A;
}
.second{
color: #07888A;
}
.third{
color: #07888A;
}
.fourth{
color: #07888A;
}
h1{
display: inline;
margin-right: 20px;
}
</style>
</head>
<body>
<h1 class="first" onClick="select('first', 'changeColor')">First</h1>
<h1 class="second" onClick="select('second', 'changeColor')">Second</h1>
<h1 class="third" onClick="select('third', 'changeColor')">Third</h1>
<h1 class="fourth" onClick="select('fourth', 'changeColor')">Fourth</h1>
</body>
</html>
Add this bit:
function select(currentColor, changeColor) {
// Get the list of the `.changeColor` elements.
changed = document.querySelectorAll(".changeColor");
// Loop through all the elements with `changeColor` class.
for (i = 0; i < changed.length; i++)
// Remove the changeColor class from their class list.
changed[i].classList.remove("changeColor");
// Rest comes your code.
if(count > 1 && flag === true){
are you trying to get one button disabled when any three buttons are enabled ? if so, perhaps this could help. I highly suggest not to use the h1 tags for this purpose, and use something like a button or div, and removing the onclick attributes from your elements and incorporate them in your main js file similar to the js snippet found below.
(function() {
//an empty array to track the number of elements currently colored
var numberOfElesColored = [],
eles = document.querySelectorAll('h1'),
//the number of active elements allowed at once
numberOfActiveElementsAllowed = eles.length - 1;
//loop though all the elements and attach click event
[].forEach.call(eles, function(ele, i) {
ele.addEventListener('click', function(event) {
var currentEle = event.target;
//is there at least two other elements avaliable still ?
if (!(numberOfElesColored.length === numberOfActiveElementsAllowed)) {
//yes
//is the current clicked element not active already ?
if (!currentEle.classList.contains('changeColor')) {
//yes
//add 1 to tracking array
numberOfElesColored.push(1);
//activate element
return currentEle.classList.add('changeColor');
} else {
//no
//remove 1 from tracking array
numberOfElesColored.pop();
//deactivate elements
return currentEle.classList.remove('changeColor');
}
//are all the elements active already ?
} else if (numberOfElesColored.length === numberOfActiveElementsAllowed) {
//yes
//is the current element an active one ?
if (currentEle.classList.contains('changeColor')) {
//yes
//remove 1 from tracking array
numberOfElesColored.pop();
//deactivate element
return currentEle.classList.remove('changeColor');
}
}
});
});
})();

Javascript : on click check boxes adding divs dynamically with pure java script not Jquery

I am beginner for java script.
I have three check boxes on my page with different ids. when I checked first check box I need to show one div. when I checked second check box include first check box , I need to split one div to two divs. As well as when i checked three boxes split one div to three divs.
I need to add all these divs dynamically with java script.
observe the below image and same like i need
Please help me to achieve this with simple java script code not with Jquery.
this took a bit of coding ;)
basically you want to append a div to the wrapper when you check a box, and remove it when you uncheck the box. Every time the DOM is changed I am running a setWidth function to apply a class used in the css to correctly position the boxes within the wrapper
checkboxes and wrapper to append the divs
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<div id="wrapper"></div>
css
#wrapper {
width: 100%;
height: 100px;
}
.box {
border: 1px solid black;
height: 100%;
display: inline-block;
box-sizing: border-box;
}
.cols-1 {
width: 100%;
}
.cols-2 {
width: 50%;
}
.cols-3 {
width: 33%;
}
JS
var checkboxes = document.getElementsByTagName('input');
var wrapper = document.getElementById('wrapper');
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.addEventListener('change', changed);
}
function changed(e) {
var el = e.target;
var num = el.value;
var checked = el.checked;
if (checked) {
addBox(num);
} else {
removeBox(num)
}
}
function addBox(num) {
var box = document.createElement('div');
box.className = 'box';
box.id = 'box-' + num;
wrapper.appendChild(box);
setWidth();
}
function removeBox(num) {
var box = document.getElementById('box-' + num);
wrapper.removeChild(box);
setWidth();
}
function setWidth() {
var children = wrapper.getElementsByTagName('div');
var i = 0, length = children.length;
for (i; i < length; i++) {
children[i].className = 'box cols-' + length;
}
}
see fiddle: http://jsfiddle.net/4hrp0qc8/1/

Categories

Resources