JQuery Classes Count in HTML - javascript

I have a HTML which is receive input from users. My job is to count cards they enter and style these cards. Cards are placed inside <section>.
Problems: My Jquery is only counting and works well in one section. If users enter more than one sections, the code doesn't work. My code below shows when users enter 2 sections: cards in first section should be blue and cards in second section should be red, but now they are all blue.
jsfiddle
var numCard = $('.cards').length;
if (numCard == "2") {
/* $('.cards').css('color', 'red'); */
$("section .cards").parent().addClass("two-cards");
} else if (numCard == "3") {
$("section .cards").parent().addClass("three-cards");
} else {
$('section .cards').parent().addClass("four-cards");
}
body {
padding: 20px;
font-family: Helvetica;
}
.two-cards .cards {
color: red;
}
.three-cards .cards {
color: green;
}
.four-cards .cards {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
<div class="cards">
Third Card
</div>
<div class="cards">
Third Card
</div>
</section>
<p>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
</section>

Working fiddle
You need to loop through the sections, then use this keyword to check :
$('section').each(function() {
var numCard = $('.cards', this).length;
if (numCard == "2") {
$(this).addClass("two-cards");
} else if (numCard == "3") {
$(this).addClass("three-cards");
} else {
$(this).addClass("four-cards");
}
});
body {
padding: 20px;
font-family: Helvetica;
}
.two-cards .cards {
color: red;
}
.three-cards .cards {
color: green;
}
.four-cards .cards {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
<div class="cards">
Third Card
</div>
<div class="cards">
Third Card
</div>
</section>
<p>
<section>
<div class="cards">
First Card
</div>
<div class="cards">
Second Card
</div>
</section>
</p>

Related

How to change background color conditionally?

I am trying to change the color of background.
I am changing every odd results to light green(#f0f5f5) so when the result ends in even number,
I get big white space.
I would like to change background color of pagination section to light green when the result ends in even number.
Sear
search results displays only 5 results so it could be 2th and 4th.
search.addWidgets([
instantsearch.widgets.searchBox({
container: '#searchbox',
}),
instantsearch.widgets.hits({
container: '#Algolia_Result',
transformItems: function (items) {
return items.map(function (item) {
if (item.objectType === 'Startup') {
item._isDescription = isNotNull(item.description);
} else if (item.objectType === 'NEWS') {
item._isSource = isNotNull(item.source);
} else if (item.objectType === 'Comment') {
item._isComment = isNotNull(item.comment);
return item;
});
},
templates: {
empty: '<div id="empty">No results have been found for {{ query }}.</div><br>',
item: `
<a href="{{linkUrl}}" target="_blank">
<div class="algolia_container">
<div class="item1">
<div id="images"><img src="{{logoUrl}}" alt="{{hits-image}}" id="hits-image"></div>
<div id="objTyeps"><span class="objectType {{objectCss}}">{{objectType}}</span></div>
</div>
<div class="item2">
<div id="objectTitle">
<span id="titleForDisplay">{{#helpers.highlight}}{ "attribute": "titleForDisplay" }{{/helpers.highlight}}</span>
</div>
</div>
<div class="item3">
{{#_isLocation}}
<div id="location">{{#helpers.highlight}}{ "attribute": "location" }{{/helpers.highlight}}</div>
{{/_isLocation}}
</div>
</div></a>
`,
},
}),
instantsearch.widgets.pagination({
container: '#pagination',
}),
]);
#Algolia_Result > div > div > ol > li:nth-child(odd){background-color: #f0f5f5;}
.ais-Pagination-item {
display:inline;
padding: 5px;
margin: 0 5px;
border: 1px solid #E8E8E8;
border-radius:5px;
font-size:18px;
}
.ais-Pagination-list {
text-align: center;
height:45px;
padding-top: 10px;
}
.ais-Pagination-item:hover {
background-color: #DCDCDC;
transition: background-color .2s;
}
.ais-Pagination-item--selected{
background-color: #E8E8E8;
}
<div id="searchbox"></div>
<div id="results">
<div id="Algolia_Result"></div>
<div id="pagination"></div>
</div>
This is ok
This need be fixed as if the background color of pagination area is the same as the last result, it must be green
This is what I get in the console.
You can color background of the pagination row by using JavaScript to count the number of results and apply color if the number of results is even.
Check out the example below.
Example 1 is with an odd number of result rows and the CSS works fine, same as your working example.
Example 2 is with an even number of result rows and uses the JS code to style the pagination background.
// Count the rows
let numRows = document.querySelectorAll('#example-2 .row').length
// If the number of rows is even
if (numRows % 2 == 0) {
// Apply the background color to the pagination row
document.querySelector('#example-2 .pagination').style.backgroundColor = '#eee'
}
.container {
border: 1px solid #000;
margin-bottom: 5px;
}
.row:nth-child(odd) {
background-color: #eee;
}
Example 1
<div id="example-1" class="container">
<div>
<div class="row">Row 1</div>
<div class="row">Row 2</div>
<div class="row">Row 3</div>
</div>
<div>
<div class="pageination">Pagination Row</div>
</div>
</div>
Example 2
<div id="example-2" class="container">
<div>
<div class="row">Row 1</div>
<div class="row">Row 2</div>
<div>
<div>
<div class="pagination">Pagination Row</div>
</div>
</div>
EDIT: So in your example, you would add the following JavaScript.
<script>
let numRows = document.querySelectorAll('.ais-Hits-item').length
if (numRows % 2 == 0) {
document.querySelector('.ais-Pagination-list').style.backgroundColor = '#eee'
}
</script>
EDIT 2: Looking at your code sandbox I can see that the issue is that the JS that counts the number of rows is being run before the rows have been rendered by Algolia.
To solve this issue we need to place our row counting JS into an Algolia callback that is ran after the rows have been rendered. We can use the algolia search.on('render', ...) event callback.
Try this:
search.on('render', () => {
let numRows = document.querySelectorAll('.algolia_container').length;
if (numRows % 2 === 0) {
document.querySelector('#pagination').style.backgroundColor = 'red';
} else {
document.querySelector('#pagination').style.backgroundColor = 'transparent';
}
});

Check if div-container has more than one div-inner no jQuery

I need a if else function that checks if div_container has more than one div_inner inside of it with Javascript only.
Here's my example code:
var inner = document.querySelector('.inner')
var container = document.querySelector('.container').innerHTML;
if(container > '1') {
container.classList.add('test');
}
else {
// do nothing
}
.test {
color: red;
}
<div class="container">
<div class="inner">Test</div>
</div>
<div class="container">
<div class="inner">Test</div>
<div class="inner">Test</div>
</div>
I only want to use Javascript. No jQuery at all.
You have to use querySelectorAll() to get all the container and loop through them to check the inner div's length:
var container = document.querySelectorAll('.container');
container.forEach(function(el){
var inner = el.querySelectorAll('.inner').length;
if(inner > 1) {
el.classList.add('test');
}
else {
// do nothing
}
});
.test {
color: red;
background-color: lightgray;
}
<div class="container">
<div class="inner">Test</div>
</div>
<div class="container">
<div class="inner">Test</div>
<div class="inner">Test</div>
</div>
You can use querySelectorAll()
for (const container of document.querySelectorAll('.container')) {
if (container.querySelectorAll('.inner').length > 1) {
container.classList.add('test');
}
}
.test {
color: red;
}
<div class="container">
<div class="inner">Test</div>
</div>
<div class="container">
<div class="inner">Test</div>
<div class="inner">Test</div>
</div>

Refactoring jQuery repeating pattern

I have painted my self into a corner in order to quickly prototype.
What's the best way to refactor the following jQuery code? Its functionality is to toggle between some sidebar navigation items. I need it to be more dynamic in order to be scalable.
Would you add the IDs inside the if statements, in an array and iterate through them? Use variables? Create a function and call it on the html side onClick? No matter what I think of, it stills leads to a bunch of repeating code.
Thank you!
// TOGGLING LEFT NAVIGATION
$('#settingsClick').click(function() {
if( $('#addContainer, #noteContainer, #logoContainer, #themeContainer').is(':visible') ) {
$('#addContainer').slideUp(350);
$('#noteContainer').slideUp(350);
$('#logoContainer').slideUp(350);
$('#settingsContainer').slideDown(350);
$('#themeContainer').slideUp(350);
} else {
$('#settingsContainer').slideToggle(350);
}
});
$('#addClick').click(function() {
if( $('#settingsContainer, #noteContainer, #logoContainer, #themeContainer').is(':visible') ) {
$('#settingsContainer').slideUp(350);
$('#noteContainer').slideUp(350);
$('#logoContainer').slideUp(350);
$('#addContainer').slideDown(350);
$('#themeContainer').slideUp(350);
} else {
$('#addContainer').slideToggle(350);
}
});
$('#noteClick').click(function() {
if( $('#settingsContainer, #addContainer, #logoContainer, #themeContainer').is(':visible') ) {
$('#settingsContainer').slideUp(350);
$('#addContainer').slideUp(350);
$('#logoContainer').slideUp(350);
$('#noteContainer').slideDown(350);
$('#themeContainer').slideUp(350);
} else {
$('#noteContainer').slideToggle(350);
}
});
$('#logoClick').click(function() {
if( $('#settingsContainer, #addContainer, #noteContainer, #themeContainer').is(':visible') ) {
$('#settingsContainer').slideUp(350);
$('#addContainer').slideUp(350);
$('#noteContainer').slideUp(350);
$('#logoContainer').slideDown(350);
$('#themeContainer').slideUp(350);
} else {
$('#logoContainer').slideToggle(350);
}
});
$('#themeClick').click(function() {
if( $('#settingsContainer, #addContainer, #noteContainer, #logoContainer').is(':visible') ) {
$('#settingsContainer').slideUp(350);
$('#addContainer').slideUp(350);
$('#noteContainer').slideUp(350);
$('#logoContainer').slideUp(350);
$('#themeContainer').slideDown(350);
} else {
$('#themeContainer').slideToggle(350);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="settingsClick">Click Me</a><br>
<div id="settingsContainer">Content...</div>
<br><br>
<a id="addClick">Click Me</a><br>
<div id="addContainer">Content...</div>
<br><br>
<p> Etc... Etc....</p>
You should group using the common CSS class, i.e. header and content. Using the established relationship you can target the others content holder and content associated with the current clicked header element.
$('.container .header').on('click', function() {
//Get the current element
var $this = $(this);
//find the content
var $content = $this.closest('.container').find('.content'); //$this.next()
//get all contents
var content = $('.container .content');
//Slide up others
content.not($content).slideUp(350);
//Slide down
$content.slideToggle(350);
});
.content {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="header" id="settingsClick">Click Me</div>
<div class="content" id="settingsContainer">Content...</div>
</div>
<div class="container">
<div class="header" id="addClick">Click Me</div>
<div class="content" id="addContainer">Content...</div>
</div>
<div class="container">
<div class="header" id="noteClick">Click Me</div>
<div class="content" id="noteContainer">Content...</div>
</div>
the best bet would be to do it like so
$(document).on('click', ".trigger", function() {
var sibling_content = $(this).siblings(".content");
if (!sibling_content.hasClass('active')) {
$(".content").slideUp('slow').removeClass('active');
sibling_content.slideDown('slow').addClass('active');
} else {
sibling_content.slideUp('slow').removeClass('active');
}
})
.trigger {
background-color: red;
color: white;
font-size: 16px;
}
.content {
background-color: blue;
color: white;
font-size: 16px;
padding: 20px 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="trigger">trigger</div>
<div class="content">content</div>
</div>
<div class="container">
<div class="trigger">trigger</div>
<div class="content">content</div>
</div>
<div class="container">
<div class="trigger">trigger</div>
<div class="content">content</div>
</div>
<div class="container">
<div class="trigger">trigger</div>
<div class="content">content</div>
</div>

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>

How to hide elements one by one then show them one by one using jquery?

Trying to hide one div at a time (5 seconds intervals between each) and when the third one gets hidden the first one shows right away. And like that infinitely.
I tried this but it's not working well. Hides them successfully but doesn't show them.
setTimeout(function() {
$('#span3').hide();
}, 5000);
setTimeout(function() {
$('#span2').hide();
}, 10000);
setTimeout(function() {
$('#span1').hide();
}, 15000);
setTimeout(function() {
$('#span3').show();
}, 15000);
setTimeout(function() {
$('#span2').show();
}, 20000);
setTimeout(function() {
$('#span1').show();
}, 25000);
.appear-span div span {
display: block;
background-color: black;
padding: 5px 0;
color: white;
width: 200px;
text-align: center;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appear-span">
<div id="span3">
<span>Selling food.</span>
</div>
<div id="span2">
<span>Selling drink.</span>
</div>
<div id="span1">
<span>Selling kidneys.</span>
</div>
</div>
Where do I add the timings if I want them to hide 5 seconds one after the other?
$("#span3").hide(function(){
$("#span2").hide(function(){
$("#span1").hide(function(){
});
});
});
Check if last div is visible, hide divs one by one and if last div is hidden, show divs one by one.
setInterval(function() {
if ($(".appear-span > div:last").is(":visible"))
$(".appear-span > div:visible").first().hide();
else
$(".appear-span > div:not(:visible)").first().show();
}, 5000);
setInterval(function() {
if ($(".appear-span > div:last").is(":visible"))
$(".appear-span > div:visible").first().hide();
else
$(".appear-span > div:not(:visible)").first().show();
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appear-span">
<div id="span3">
<span>Selling food.</span>
</div>
<div id="span2">
<span>Selling drink.</span>
</div>
<div id="span1">
<span>Selling kidneys.</span>
</div>
</div>
You can try something like this.
Logic
Hide all divs and show div that is to be shown.
You can use .eq to find element at necessary position
var counter = -1;
function updateUIState(){
$('[id^="span"]').hide().eq(++counter % 3).show()
initTimeout();
}
function initTimeout(){
setTimeout(updateUIState, 1000)
}
initTimeout();
.appear-span div span {
display: block;
background-color: black;
padding: 5px 0;
color: white;
width: 200px;
text-align: center;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="appear-span">
<div id="span3">
<span>Selling food.</span>
</div>
<div id="span2">
<span>Selling drink.</span>
</div>
<div id="span1">
<span>Selling kidneys.</span>
</div>
</div>
Just nest the calls and then recall the same function, use jquery delay.
$(function() {
var delayInterval = 5000;
function hideAndPeek() {
$('#span3').delay(delayInterval).hide(function() {
$('#span2').delay(delayInterval).hide(function() {
$('#span1').delay(delayInterval).hide(function() {
$('#span3').delay(delayInterval).show(function() {
$('#span2').delay(delayInterval).show(function() {
$('#span1').delay(delayInterval).show(function() {
hideAndPeek();
});
});
});
});
});
});
}
setTimeout(hideAndPeek(), delayInterval);
});
p {
font-size: 150%;
cursor: pointer;
}
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appear-span">
<div id="span3">
<span>Selling food.</span>
</div>
<div id="span2">
<span>Selling drink.</span>
</div>
<div id="span1">
<span>Selling kidneys.</span>
</div>
</div>
</body>

Categories

Resources