How to make simple 3 step checkout section like quiz - javascript

Hello and have a nice day!
I want to create simple step by step element with back button.
I have a next markup
<div class="checkout">
<div class="checkout-step">
<div class="content">This is step 1</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
<div class="checkout-step">
<div class="content">This is step 2</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
<div class="checkout-step">
<div class="content">This is step 3</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
</div>
JS (It's not fully complete code, just part of existing code, I don't fully understand how I can do it)
var checkoutStepCounter = 0;
var checkoutStepLength = $('.checkout-step').length;
$('.button-next-step').click(function() {
checkoutStepCounter++;
if( checkoutStepLength < checkoutStepCounter ) {
$(this).find('.checkout-step').hide();
$(this).find('.checkout-step').next('.checkout-step').show();
}
});
$('.button-prev-step').click(function() {
checkoutStepCounter--;
if( checkoutStepLength < checkoutStepCounter ) {
$(this).find('.checkout-step').hide();
$(this).find('.checkout-step').prev('.checkout-step').show();
}
});
CSS:
.button-prev-step, .button-next-step { display: block; width: 100px; height: 20px; background: red; cursor: pointer; }
.checkout-step { display: none; }
https://codepen.io/Frunky/pen/yKNMOM
How to make function nextStep and prevStep? in result I want to slide between the sections, and in total - send filled data to backend. Now I need to add an ability to slide between .checkout-step blocks. May be I need to add simple slider? like slick or owl, but I don't know if it's right way or not

Simple code snippet to show you next and previous button working. You can do some more research and add your desired animation (slide, fade etc.) as per your requirements.
var checkoutSteps = 3;
var currentStep = 1;
$('.button-next-step').click(function() {
if(currentStep < checkoutSteps){
$(".checkout-step-"+currentStep+"").hide();
currentStep++;
$(".checkout-step-"+currentStep+"").show();
}
});
$('.button-prev-step').click(function() {
if(currentStep > 1){
$(".checkout-step-"+currentStep+"").hide();
currentStep--;
$(".checkout-step-"+currentStep+"").show();
}
});
.button-prev-step, .button-next-step { display: inline-block; width: 100px; height: 20px; background: red; cursor: pointer; }
.checkout-step {
width: 300px;
height: 300px;
border: 1px solid #000;
display: none;
}
.checkout-step-1{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkout">
<div class="checkout-step checkout-step-1">
<div class="content">This is step 1</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
<div class="checkout-step checkout-step-2">
<div class="content">This is step 2</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
<div class="checkout-step checkout-step-3">
<div class="content">This is step 3</div>
<div class="button-prev-step">Previous step</div>
<div class="button-next-step">Next step</div>
</div>
</div>
Hope this helps

Related

Scroll to bottom when new message added

I am making a chatbot. I want to scroll to the bottom of the chat box when a new input is given by the user or the Data is sent through API.
It doesn't scroll and scroll just stays in the same position but the data is being added in the chat box
I Have tried the code from other chat bot but it didn't work either
var outputArea = $('#chat-output');
$('#user-input-form').on('submit', function (e) {
e.preventDefault();
var message = $('#user-input').val();
outputArea.append(`
<div class='bot-message'>
<div class='message'>
${message}
</div>
</div>
`);
const req = https.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (d) => {
const myobj = JSON.parse(d);
if ('narrative' in myobj.conversationalResponse.responses[0]) {
const temp = myobj.conversationalResponse.responses[0].narrative.text;
outputArea.append(`
<div class='user-message'>
<div class='message'>
${temp}
</div>
</div>
`);
} else if ('imageUrl' in myobj.conversationalResponse.responses[0]) {
const img = myobj.conversationalResponse.responses[0].imageUrl;
if ('narrative' in myobj.conversationalResponse.responses[1]) {
const text_r = myobj.conversationalResponse.responses[1].narrative.text;
outputArea.append(`
<div class='user-message'>
<div class ="message">
${text_r}
</div>
</div>
`);
} else {
outputArea.append(`
<div class='user-message'>
<div class='message'>
<img src="" width="300" height="200">
</div>
</div>
`);
}
}
});
});
req.on('error', (error) => {
console.error(error);
});
req.write(data);
req.end();
$('#user-input').val('');
.form-container {
width: 400px;
height: 450px;
padding: 10px;
background-color: white;
overflow: scroll;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chat-popup" id="myForm">
<div class="form-container">
<div class="chat-output" id="chat-output">
<div class="user-message">
<div class="message">Hi! I'm Bot, what's up?</div>
</div>
</div>
<div class="chat-input">
<form action="#0" id="user-input-form" autocomplete="off">
<input type="text" id="user-input" class="user-input" placeholder="Talk to the bot.">
</form>
</div>
</br></br>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</div>
</div>
Another interesting method is by using pure CSS, using the flex-direction method, which works by creating a wrapper for the content inside the scrolling element.
I've whipped up a quick demo below (with a button and some JavaScript for adding new items). You can also check out this separate demo-page.
The trick then lies in reversing the content direction using column-reverse in the scroller. Because the items are in another container, they don't get 'flipped' but instead always line up to the bottom. This, in fact, makes the scroller scrolled to the bottom whenever stuff is added.
Added bonus: keeps scroll position
Also, and this is something I really like about the method; whenever the user has started scrolling (up), the scroller will not lose its scroll position when stuff is being added. So, it will only 'stick' tot the bottom if it was already scrolled (by default, or by the user) to the bottom. This makes sure there's no annoying content jumping, offering a better user experience.
Demo
let scrollerContent = document.getElementById('scrollerContent');
document.getElementById('addItems').addEventListener('click', function() {
let newChild = scrollerContent.lastElementChild.cloneNode(true);
newChild.innerHTML = "Item " + (scrollerContent.children.length + 1);
scrollerContent.appendChild(newChild);
});
.scroller {
overflow: auto;
height: 100px;
display: flex;
flex-direction: column-reverse;
}
.scroller .scroller-content .item {
height: 20px;
transform: translateZ(0); /* fixes a bug in Safari iOS where the scroller doesn't update */
}
<div class="scroller">
<div class="scroller-content" id="scrollerContent">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
<div class="item">Item 8</div>
<div class="item">Item 9</div>
<div class="item">Item 10</div>
</div>
</div>
<br/><br/>
<button id="addItems">Add more items</button>
You can use scrollTop to achieve it.
I simply wrote an example for your reference, you will find that there are two ways to implement scrollTop, one is to use the animation wrapper, the other is to use it directly, you can compare the difference between the two methods.
const sendMessage = (selector, isAnimate = true) => {
const text = $(selector).val();
const $container = $('.form-container');
$container.append(`<p>${text}</p>`);
if (isAnimate) {
$container.animate({
scrollTop: $container.prop('scrollHeight')
}, 1000);
} else {
$container.scrollTop($container.prop('scrollHeight'));
}
$(selector).val('');
};
$('button:eq(0)').on('click', function() {
sendMessage('input[type=text]');
});
$('button:eq(1)').on('click', function() {
sendMessage('input[type=text]', false);
});
.form-container {
width: 400px;
height: 100px;
padding: 10px;
background-color: white;
overflow: scroll;
position: relative;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div class='form-container'>
<p>This is line 1 of text</p>
<p>This is line 2 of text</p>
</div>
<div>
<input type='text' placeholder="Type a message.">
<button type='button'>Use animation</button>
<button type='button'>Don't use animation</button>
</div>
This worked for me:
outputArea[0].scrollTop = 9e9;

replace a div hidden intially by a click on a link from 3 other 3 linkes(3 other divs)

Hi I want to replace a div that is already displayed with another Hidden div choosed when i click on one of them(3 other divs(hidden) initially). the 4 links related to the 4 divs and in same way i can do that in each link clicked. below is the code:
<script type="text/javascript">
#4 Id of divs
var models = document.getElementById('models')
var geometry = document.getElementById('geometry')
var assembly = document.getElementById('assembly')
var loads = document.getElementById('loads')
#4 ID OF links (related to each div)
var models1 = document.getElementById('models1')
var geometryy = document.getElementById('geometryy')
var assemblyy = document.getElementById('assemblyy')
var loads1 = document.getElementById('loads1')
geometryy.addEventListener("click", function () {
models.style.display = "none"
loads.style.display = "none"
assembly.style.display = "none"
geometry.style.display = "block"
})
assemblyy.addEventListener("click", function () {
geometry.style.display = "none"
models.style.display = "none"
loads.style.display = "none"
assembly.style.display = "block"
})
loads1.addEventListener("click", function () {
geometry.style.display = "none"
models.style.display = "none"
assembly.style.display = "none"
loads.style.display = "block"
})
models1.addEventListener("click", function () {
models.style.display = "block"
geometry.style.display = "none"
assembly.style.display = "none"
loads.style.display = "none"
})
</script>
CSS:
<style>
#loads {
display: none;
}
#geometry {
display: none;
}
#assembly {
display: none;
}
#models {
display: block;
}
</style>
some Html code about the 4 divs:
<form action="{% url 'results' %}" method="post" id="gallery" novalidate onsubmit="return mySubmitFunction(event)">
<div style="padding-top: 10px; margin-left:138px;" class="parallax-window tm-section tm-section-gallery tm-flex background " id="models" >
<div style=" background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
<a class="floated" style="font-weight: bolder; border-style: solid;" id="models1">Models</a>
Geometry
Assembly
Loads
</nav>
</div>
.......... some fields related to the div id="models"
</div>
</div>
----------------About the second div
<div style="padding-top: 10px;" class="parallax-window tm-section tm-section-gallery tm-flex" id="geometry" >
<div style=" background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
Models
<a class="floated" style=" font-weight: bolder; border-style: solid;">Geometry</a>
Assembly
Loads
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
----------------About the third div
<div style="padding-top: 10px;" class="parallax-window tm-section tm-section-gallery tm-flex" id="assembly" >
<div style="background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem; ">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
Models
Geometry
<a class="floated" style=" font-weight: bolder; border-style: solid;">Assembly</a>
<a href="#loads" class="floated" style=" font-weight: bolder;" id="loads3" >Loads</a>
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
----------------About the fourth div
<div style="padding-top: 10px; " class="parallax-window tm-section tm-section-gallery tm-flex" id="loads" >
<div style="background-color: white; font-size:89%; width: 62rem; height: 32rem; margin-left:2.5rem;">
<div class="card-warning" style="background-color: #C0C0C0;">
<nav class="navbar">
<a href="#models" class="floated" style="font-weight: bolder;" >Models</a>
Geometry
Assembly
<a style=" font-weight: bolder; border-style: solid;">Loads</a>
</nav>
</div>
<div style="display: flex;">
<div>
<img style="height: 372px; width:270px; margin-left: 25px;">
</div>
<div style="line-height: 0.001; margin-left: 10px; margin-top: 12px;">
------ some code for some fields
</div>
</div>
...... </div>
---- </div>
</form>
what i want :at first the "models" div is shown and the other 3 divs("geometry",assembly","loads") are hidden , so i want when i click on "geometry" div , the first div "models" become hidden and the other divs ("assembly" and "loads" still hidden) and so on if click on assembly... i i want to apply that on every div(because evry div has the 4 links)
But it doesn't give me any result!
<html>
<head>
<style>
#div2, #div3, #div4{
display: none;
}
</style>
</head>
<body>
<div style="background-color: #C0C0C0 ;padding-top: 10px;width: 62rem; height: 32rem; ">
<div>
<a href="#models" class="geo wy" style="border-style: solid;" >Models</a>
Geometry
Assembly
Loads
</div>
<div id="div1" class="wy hid">
Models and other stuffs here
</div>
<div id="div2" class="pk hid">
Geometry and other stuffs here
</div>
<div id="div3" class="fk hid">
Assembly and other stuffs here
</div>
<div id="div4" class="gk hid">
Loads and other stuffs here
</div>
</div>
<script>
window.onload = btn() ;
function btn() {
var query = document.querySelectorAll(".geo") ; //No of hrefs
var pts = document.querySelectorAll(".hid"); //No of divs
for(var i=0;i<query.length;i++){
query[i].addEventListener("click", function() { //know which href is being clicked currently
var cla = this.getAttribute('class').split(' ')[1] ; //get second class of current href which would be wy, pk, fk, gk respectively.
var point = document.querySelectorAll("."+cla)[1]; //selecting the div as, [0] would select the href
for(var j=0;j<pts.length;j++){
pts[j].style.display = "none"; //hid all the div
query[j].style.border= "none"; //remove all the href border
}
this.style.border= "solid"; //Add currently clicked href border
point.style.display = "block"; //display currently clicked div
})
}
}
</script>
</body>
</html>
Sorry the id and classes name are given random i am not good at naming. Please don't hesitate to ask if you are confused

jQuery - Display text when hovered on through `for` loop

I am making a webpage and I am adding a feature; when you hover on a certain div another div will display a certain text. There are 5 elements I want to be able to hover and display text.
I added this feature but it did not work properly - only the last hoverable div displayed the text. I isolated the elements used and moved them to a sandbox to tweak them. No matter what I do (I got it to work by using a bunch of if statements, but I am trying to remove that so it looks neater), only the last div will display the text.
Here is a fiddle of the working version with the many if statements:
https://codepen.io/SynergyOfLife/pen/qBNJboR
setInterval(function(){
var dataArray = ["1","2","3","4","5"]
var isHovered1 = $(`.${dataArray[0]}`).is(":hover");
var isHovered2 = $(`.${dataArray[1]}`).is(":hover");
var isHovered3 = $(`.${dataArray[2]}`).is(":hover");
var isHovered4 = $(`.${dataArray[3]}`).is(":hover");
var isHovered5 = $(`.${dataArray[4]}`).is(":hover");
if (isHovered1) {
$('p').html("TEST")
} else if (isHovered2) {
$('p').html("TEST")
}else if (isHovered3) {
$('p').html("TEST")
} else if (isHovered4) {
$('p').html("TEST")
}else if (isHovered5) {
$('p').html("TEST")
} else {
$('p').html("")
}
}, 300);
div {
height:100px;
width: 100px;
background: blue;
float: left;
}
.viewer {
height: 500px;
width: 500px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<a>Test</a>
</div>
<div class="2">
<a>Test</a>
</div>
<div class="3">
<a>Test</a>
</div>
<div class="4">
<a>Test</a>
</div>
<div class="5">
<a>Test</a>
</div>
<div class="viewer">
<p></p>
</div>
Here is the version I am trying to perfect:
https://codepen.io/SynergyOfLife/pen/VwjELME
setInterval(function(){
var dataArray = ["1","2","3","4","5"]
var i;
for (i = 0; i < dataArray.length; i++) {
var isHovered = $(`.${dataArray[i]}`).is(":hover");
if (isHovered) {
$('p').html("TEST")
} else {
$('p').html("")
}
}
}, 300);
div {
height:100px;
width: 100px;
background: blue;
float: left;
}
.viewer {
height: 500px;
width: 500px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<a>Test</a>
</div>
<div class="2">
<a>Test</a>
</div>
<div class="3">
<a>Test</a>
</div>
<div class="4">
<a>Test</a>
</div>
<div class="5">
<a>Only working div?</a>
</div>
<div class="viewer">
<p></p>
</div>
In summary, I am asking for help on how to shorten the number of if statements
Just use the hover() method which accepts two functions, one for mouseenter and one for mouseleave.
var dataArray = ["1", "2", "3", "4", "5"]
var selectors = '.' + dataArray.join(',.');
$(selectors).hover(function() {
// `this` is the element the event occurred on
$('p').html('TEST ' + this.className)
}, function() {
$('p').empty()
})
div {
height: 100px;
width: 100px;
background: blue;
float: left;
}
.viewer {
height: 500px;
width: 500px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="1">
<a>Test</a>
</div>
<div class="2">
<a>Test</a>
</div>
<div class="3">
<a>Test</a>
</div>
<div class="4">
<a>Test</a>
</div>
<div class="5">
<a>Test</a>
</div>
<div class="viewer">
<p></p>
</div>

How to save the details of range slider in the local storage?

I am replicating this webpage https://www.modsy.com/project/furniture and I wrote the code On every slide there will be changing of image and phrase like that there are three phrases and images now I want to store the image and phrase in the local storage what the user has finalized
My html code is:
<div class="image mt-3 mb-3" id="sliderImages">
<img src="../static/images/1.jpg" width="400" height="180">
<img src="../static/images/2.jpg" width="400" height="180">
<img src="../static/images/3.jpg" width="400" height="180">
</div><br>
<div class="rangeslider">
<input type="range" min="1" max="3" value="1" class="myslider" id="sliderRange">
<div id="sliderOutput">
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
<div class="container">
<div class="row mt-4">
<div class="col-4">
<h6 class="display-6">Starting From Scratch</h6>
<p> I'm designing the room </p>
</div>
<div class="col-4">
<h6 class="display-6">Somewhere in Between</h6>
<p>I'm designing around a few pieces I already own</p>
</div>
<div class="col-4">
<h6 class="display-6">Mostly Furnished</h6>
<p>I want to put the finishing touches on my room</p>
</div>
</div>
</div>
</div>
<div class="row mb-3 mt-3">
<div class="col-4 mr-5">
« Home
</div>
<div class="col-4 ml-5">
Next » </div>
</div>
</div>
My CSS code is:
<style>
.rangeslider {
width: 50%;
margin: 0 auto;
position: absolute;
}
.myslider {
-webkit-appearance: none;
background: white;
width: 100%;
height: 20px;
opacity: 0.8;
margin-top: 180px;
}
.myslider::-webkit-slider-thumb {
-webkit-appearance: none;
cursor: pointer;
background: #000080;
width: 33%;
height: 20px;
}
.col-4 {
text-align: center;
}
.myslider:hover {
opacity: 1;
}
.image {
position: relative;
width: 400px;
margin: 0 auto;
}
.image>img {
position: absolute;
display: none;
}
.image>img.visible,
.image>img:first-child {
display: block;
}
#sliderOutput>div {
display: none;
}
#sliderOutput>div.visible,
#sliderOutput>div:first-child {
display: block;
}
#p1{
height: 10px;
}
</style>
My JS code is:
<script>
window.addEventListener('load', function() {
var rangeslider = document.getElementById("sliderRange");
var output = document.getElementById("sliderOutput");
var images = document.getElementById("sliderImages");
rangeslider.addEventListener('input', function() {
for (var i = 0; i < output.children.length; i++) {
output.children[i].style.display = 'none';
images.children[i].style.display = 'none';
}
i = Number(this.value) - 1;
output.children[i].style.display = 'block';
images.children[i].style.display = 'block';
});
});
</script>
My main requirement if the slider is in the first that phrase and image should be stored in local storage like that if it is in second that details should store.
There is no enough details about what json you want to store in the localStorage so that's why i am giving you the basic idea of how you can store a json in localStorage.
Basically you can't store json in localStorage directly but you can store that json in form of a stringand then converting that string(json) into json. Here is the basic example :
// setting json to localStorage
var jsonToBeStoredInLocalStorae = {
sliderImages = [
{path : 'image-path-here'},
{path : 'image-path-here'}
],
phrase : 'your image phrase'
};
localStorage.setItem('slider_json',JSON.stringify(jsonToBeStoredInLocalStorae ));
When you want to get that json from localStorage so you will do like this
//Here you are getting that json in `string` form from `localStorage` and parsing it to `json`
var localStorageJson = JSON.parse(localStorage.getItem('slider_json'));
In localStorage you can only save text strings, so if you want to save it is only one value per record, you insert a name and value to localStorage, but if you want to save an object, you must transform it to a text string with the function JSON.stringify

Creating a star rating from an image based on a float number?

recently I have wanted to turn a number into a star rating and I stumbled upon this post here: https://stackoverflow.com/a/1987545/1871869 which is exactly what I wanted to do. I have followed this explanation but I can't seem to get it to work on my local environment, and I was wondering if someone could help me out. Here is my attempt:
$.fn.stars = function() {
return $(this).each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars holder
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
}
$(function() {
console.log("Calling stars()");
$('.results-contents span.stars').stars();
});
.results {
font-size: 0;
padding-bottom: 16px;
}
.results-content {
font-size: 13px;
display: inline-block;
margin-left: 20px;
vertical-align: top;
}
.results .results-content span.stars span.stars span {
background: url('/resources/graphics/stars-icons.png') 0 -36px repeat-x;
width: 175px;
height: 80px;
}
.results .results-content span.stars {
max-width: 80px;
background-position: 0 0;
}
<script type="text/template" id="results-template">
<div class="results">
<div class="results-content">
<span class="stars">4.0</span>
</div>
</div>
</script>
Image of stars:
What I wanted to do was to simply have the empty stars show, and then based on the rating, show the orange stars on top of the empty stars so that I can show full and half star ratings. However, all I get is a number to show up. My console.log above seems to be called but it seems like the actual rendering of the image and calculation of the star rating is not working. Any help would be appreciated. Thanks!
You had multiple issues from CSS styles being wrong to your selector being wrong. Below is not perfect, but it is rendering.
$.fn.stars = function() {
return this.each(function() {
// Get the value
var val = parseFloat($(this).html());
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 36.5;
// Create stars holder
var $span = $('<span> </span>').width(size);
// Replace the numerical value with stars
$(this).empty().append($span);
});
}
$(function() {
console.log("Calling stars()");
$('.results-content span.stars').stars();
});
.results {
font-size: 0;
padding-bottom: 16px;
}
.results-content {
font-size: 13px;
display: inline-block;
margin-left: 20px;
vertical-align: top;
background: url('https://i.stack.imgur.com/rwkqF.png') 0 0 repeat-x;
width: 185px;
height: 35px;
}
.results .results-content span.stars span {
background: url('https://i.stack.imgur.com/rwkqF.png') 0 -36px repeat-x;
display: inline-block;
height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
<div class="results-content">
<span class="stars">0.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">0.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">1.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">1.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">2.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">3.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">3.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">4.0</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">4.5</span>
</div>
</div>
<div class="results">
<div class="results-content">
<span class="stars">5.0</span>
</div>
</div>

Categories

Resources