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

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>

Related

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

Modal Window on card click JS CSS PHP

So I have 6 cards on my html. Each one on click need to pop up a modal window (this modal window is the card with more informations, so each modal window is corresponding to one card).
I dont know how to do that. After a day searching on the web I'm here to ask your help.
I have tried to make the html animal_card, and my modal appart. Then all the content will change with php.
And the Javascript need to change the modal window css property to absolute on click.
Someone know how to do that with Javascript ?
HTML :
<div class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close" onclick="closeModal()">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
CSS :
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
position: absolute;
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
Javascript :
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const onCardClick = async (e) => {
const card = e.currentTarget;
modal.style.position = 'absolute';
}
cards.forEach(card => card.addEventListener('click', onCardClick));
function closeModal() {
modal[0].style.position = 'none';
}
const cards = document.querySelectorAll('.animal_card');
const modal = document.getElementsByClassName('bg-modal');
const getKeyMap = (modal) => {
if (modal) {
let i;
let keyMap = {};
for (i = 0; i < modal.length; i++) {
const item = modal[i];
const key = item.getAttribute('key');
keyMap[key] = item;
}
return keyMap;
}
return null;
};
const modalMap = getKeyMap(modal);
const onCardClick = async (e) => {
const card = e.currentTarget && e.currentTarget.getAttribute('key') || null;
const selectedModal = modalMap[card] || null;
if (selectedModal) {
selectedModal.style.position = 'absolute';
}
}
cards.forEach(card => card.addEventListener('click', onCardClick));
.bg-modal {
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
/* position: absolute; */
top: 0;
left: 0;
display: flex;
justify-content: center;
}
.modal-content {
position: absolute;
margin-top: 5rem;
width: 75vw;
background-color: $white;
border-radius: 15px;
}
<div key="5" class="animal_card">
<div class="card_title">
<h3>title</h3>
</div>
<div class="card_image">
<img src="image.img" alt="">
</div>
<div class="card_text">
<div class="card_info">
<div class="card_info_age">
<h4>Age</h4>
<p>14</p>
</div>
<div class="card_info_gender">
<h4>Gender :</h4>
<p>Female</p>
</div>
</div>
<h4>Who am I</h4>
<p>Description Text</p>
</div>
</div>
<div class="bg-modal" key="5">
<div class="modal-content">
<div class="modal-animal">
<h1>Animal Name</h1>
<button class="close">&times</button>
<div><img src="img/greciaprofile.jpg" alt=""></div>
<div class="animal-informations">
<div class="left">
<label for="">Age</label>
<p>14</p>
<label for="">Sexe</label>
<p>Female</p>
</div>
<div class="right">
<label for="">Description</label>
<p>
Text
</p>
</div>
</div>
<div>
<button class="main">Adopt</button>
<button class="secondary">Support</button>
</div>
</div>
</div>
</div>
So the direct answer using your example is modal on the onCardClick is returning a collection, not a single element. So selecting the first one modal[0] will fix the position update. I attached an example.
If you are going to show different modals based on the card you click on, you generally need to have a method to track them. Really depends on how you want to do that, based on ids, or index position or so on. Anyways, let me know if this helps.

How to make simple 3 step checkout section like quiz

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

Limit count of elements in div

I have div with questions
Here is it
Here is code for it
<div class="listdivright">
<div style="height: 80%; width: 100%; overflow: auto">
#foreach (var item in Model)
{
<div class="title" style="margin-top:15px;margin-left:15px; margin-bottom: 10px;">
<img class="click" src="#Url.Content("~/Images/plus_plus.png")" />
<span>
#Html.TextBoxFor(modelItem => item.question, new {#class="testclass", #readonly = "readonly" })
</span>
<a class="click2" style="margin-left:10px;">
<img src='#Url.Content("~/Images/arrow.png")' />
</a>
<a style="margin-left:25px;" href='#Url.Action("Edit", "Questions", new {id = item.QuestionId})'>
<img src='#Url.Content("~/Images/Edit.png")' />
</a>
<a href='#Url.Action("Delete", "Questions", new {id = item.QuestionId})'>
<img src='#Url.Content("~/Images/Delete.png")' />
</a>
</div>
<div class="content" style="margin-left:60px; width: 80%; height: 100px; background: white">
<div style="width: 100%">
<div style="float:left; width: 50%;">
<b>#Html.LabelFor(modelItem=>item.TimeForAnswer)</b>
<b>:</b>
<span>#Html.DisplayFor(modelItem=>item.TimeForAnswer)</span>
</div>
<div style="float:right;width: 50%;">
<b>#Html.LabelFor(modelItem => item.TimeForReady)</b>
<b>:</b>
<b>#Html.DisplayFor(modelItem => item.TimeForReady)</b>
</div>
</div>
<div style="width: 100%; text-align: center;" >
<b>#Html.LabelFor(modelItem => item.Retries)</b>
<b>:</b>
<b>#Html.DisplayFor(modelItem => item.Retries)</b>
</div>
</div>
}
</div>
I use JS to move block to left div
Code of JS script
<script type="text/javascript" >
$('.title').on('click', function () {
$(this).next().toggle();
});
$('.click2').click(function () {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
});
Here is code of left div
<div class="listdivleft">
<div style="height: 80%; width: 100%; overflow: auto">
<div class="title2" style="margin-top: 15px; margin-left: 15px; margin-bottom: 15px;padding-top: 10px">
</div>
</div>
</div>
I need to limit blocks in left div. From 0 to 10.
So it can be 0 or not more than 10
How I can do this?
You can check that if element with class title are less than 10 using length property, in that case only the new html should be appended, something like:
if($(".title").length < 10) {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
}
else {
alert("No more than 10 allowed.");
}
or if title class is reused other places as well on page, then restrict it to current parent element using listdivright class element in combination with closest and find :
if($(this).closest(".listdivright").find(".title").length < 10) {
var elem = $(this).closest('.title');
$('.title2').append($(elem).html()).show();
}
else {
alert("No more than 10 allowed.");
}
Hope it helps and gives you idea how it can be done.

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