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';
}
});
Related
I have a big list of getElementsById that looks like this:
let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bpLongDistanceHiking = document.getElementById("bp-longDistanceHiking");
let bpThruHiking = document.getElementById("bp-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");
I won't go into details, is there any way that I can loop throught all of them and for example hide all except bpLongDistanceHiking and bpThruHiking .
I had this function but that is not good way for sure:
function hideAllExceptbP() {
ahSummerCamps.style.display = "none";
ahTrekking.style.display = "none";
/* ... and for all of them like this except bpLongDistanceHiking and bpThruHiking */
}
So on that way I need function for every element like:
function hideAllExceptaH() {
/* ... + 10 lines */
function hideAllExceptC() {
/* ... + 10 lines */
function hideAllExceptE() {
/* ... + 10 lines */
Function
function choice() {
backpacking.addEventListener("click", () => {
hideBackpacking();
hideSafari();
hidePackageHoliday();
showBackpackingOptions();
console.log("Backpacking");
});
So as you can see from html I have 8 divs at start, and when user click on backpacking for example function should hide all divs except bpLongDistanceHiking and bpThruHiking
Full code calling function:
HTML:
<div class="row">
<!--main divs-->
<div style="background-color: #4cc9f0" class="column" id="adventureHolidays"><p>Adventure Holidays</p></div>
<div style="background-color: #4895ef" class="column" id="backpacking"><p>Backpacking</p></div>
<div style="background-color: #4361ee" class="column" id="cruiseHolidays"><p>Cruise Holidays</p></div>
<div style="background-color: #4361ee" class="column" id="eventTravel"><p>Event Travel</p>
</div>
<div style="background-color: #3a0ca3" class="column" id="packageHoliday"><p>Package Holiday</p></div>
<div style="background-color: #480ca8" class="column" id="safari"><p>Safari</p></div>
<div style="background-color: #560bad" class="column" id="skiingAndSnowboarding"><p>Skiing and Snowboarding</p>
</div>
<div style="background-color: #7209b7" class="column" id="volunteering"><p>Volunteering</p></div>
<!--end on main divs-->
<!--sub divs-->
<div style="background-color: #4cc9f0" class="column" id="aH-summerCamps"><p>Summer camps</p></div>
<div style="background-color: #4895ef" class="column" id="aH-trekking"><p>Trekking</p></div>
<div style="background-color: #4361ee" class="column" id="bP-longDistanceHiking"><p>Long Distance Hiking</p></div>
<div style="background-color: #4361ee" class="column" id="bP-thruHiking"><p>Thru Hiking</p></div>
<div style="background-color: #3a0ca3" class="column" id="c-oceanCruising"><p>Ocean Cruising</p></div>
<div style="background-color: #480ca8" class="column" id="c-riverCruising"><p>River Cruising</p></div>
<div style="background-color: #560bad" class="column" id="e-recreationsEvent"><p>Recreations Events</p></div>
<div style="background-color: #7209b7" class="column" id="e-sportsEvents"><p>Sports events</p></div>
<div style="background-color: #4cc9f0" class="column" id="pH-escortedTours"><p>Escorted Tours</p></div>
<div style="background-color: #4895ef" class="column" id="pH-independentTours"><p>Independent Tours</p></div>
<div style="background-color: #4361ee" class="column" id="s-photographicSafari"><p>Photographic Safari</p></div>
<div style="background-color: #4895ef" class="column" id="s-cyclingSafari"><p>Cycling Safari</p></div>
<div style="background-color: #3a0ca3" class="column" id="sAs-backcountrySkiing"><p>Backcountry skiing</p></div>
<div style="background-color: #560bad" class="column" id="sAs-downhillSkiing"><p>Downhill skiing</p></div>
<div style="background-color: #4361ee" class="column" id="v-childcare"><p>Childcare</p></div>
<div style="background-color: #4895ef" class="column" id="v-conservationAndEnvironment"><p>Conservation And
Environment</p></div>
</div>
<script type="text/javascript" th:src="#{/js/index.js}"></script>
js:
let adventureHolidays = document.getElementById("adventureHolidays");
let backpacking = document.getElementById("backpacking");
let cruiseHolidays = document.getElementById("cruiseHolidays");
let eventTravel = document.getElementById("eventTravel");
let packageHoliday = document.getElementById("packageHoliday");
let safari = document.getElementById("safari");
let skiingAndSnowboarding = document.getElementById("skiingAndSnowboarding");
let volunteering = document.getElementById("volunteering");
/*End of inserting main variables*/
/*sub variables*/
let ahSummerCamps = document.getElementById("aH-summerCamps");
let ahTrekking = document.getElementById("aH-trekking");
let bPLongDistanceHiking = document.getElementById("bP-longDistanceHiking");
let bPThruHiking = document.getElementById("bP-thruHiking");
let cOceanCruising = document.getElementById("c-oceanCruising");
let cRiverCruising = document.getElementById("c-riverCruising");
let eRecreationsEvent = document.getElementById("e-recreationsEvent");
let eSportsEvent = document.getElementById("e-sportsEvents");
let phEscortedTours = document.getElementById("ph-escortedTours");
let phIndependentTours = document.getElementById("ph-independentTours");
let sPhotographicSafari = document.getElementById("s-photographicSafari");
let sCyclingSafari = document.getElementById("s-cyclingSafari");
let sAsBackcountrySkiing = document.getElementById("sAs-backcountrySkiing");
let sAsDownhillSkiing = document.getElementById("sAs-downhillSkiing");
let vChildcare = document.getElementById("v-childcare");
let vConservationAndEnvironment = document.getElementById("v-conservationAndEnvironment");
/*end of subs variables*/
const divs = ["adventureHolidays", "backpacking", "cruiseHolidays", "eventTravel", "packageHoliday", "safari", "skiingAndSnowboarding", "volunteering", "aH-summerCamps", "aH-trekking", "bP-longDistanceHiking", "bP-thruHiking", "c-oceanCruising", "c-riverCruising", "e-recreationsEvent", "e-sportsEvents", "ph-escortedTours", "ph-independentTours", "s-photographicSafari", "s-cyclingSafari", "sAs-backcountrySkiing", "v-conservationAndEnvironment", "sAs-downhillSkiing", "v-childcare"]
.map(id => document.getElementById(id)); // gives you an array of those elements
function hideAllDivsExcept(id) {
for (const div of divs) div.hidden = !div.id === id;
}
window.onload = function () {
choice();
};
/* start of function choice for user clicks*/
function choice() {
backpacking.addEventListener("click", () => {
hideAllDivsExcept('adventureHolidays');
console.log("Backpacking");
})
}
CSS:
* {
box-sizing: border-box;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
/*
display: table;
*/
clear: both;
}
I'm getting:
index.js:38 Uncaught TypeError: Cannot read properties of null (reading 'id')
at hideAllDivsExcept (index.js:38:47)
at HTMLDivElement.<anonymous> (index.js:51:9)
And that is this
function hideAllDivsExcept(id) {
this > for (const div of divs) div.hidden = !div.id === id;
}
One approach to the problem is as below, with explanatory comments in the code:
// defining a named function to handle clicks on the 'filter' elements, that takes one
// argument, a reference to the Event Object:
const showRelevant = (evt) =>{
// caching a reference to the element to which the function is bound as the
// event-handler:
let source = evt.currentTarget,
// retrieving the attribute-value from the custom data-* attribute, using the
// HTMLElement.dataset API:
category = source.dataset.category;
// retrieving all <div> elements that do not have a "data-category" attribute which
// are the children of a .row element; we iterate over that collection using
// NodeList.prototype.forEach():
document.querySelectorAll('.row > div:not([data-category])').forEach(
// using an Arrow function we pass in a reference to the current
// Node of the NodeList over which we're iterating:
(el) => {
// we split the element's id property-value at the '-' character,
// and retrieve the first element of the resulting Array:
let prefix = el.id.split('-')[0];
// if the chosen category is exactly equal to 'all':
if (category === 'all') {
// we want to show all elements, therefore we set the hidden property
// of every element to false; so every element is shown:
el.hidden = false;
} else {
// otherwise, if the category is not equal to the prefix (above) the
// assessment results in true and so the element is hidden; if the
// category is equal to the prefix (therefore the current element is
// one we wish to see) the assessment results in false, and so the
// element is shown:
el.hidden = category !== prefix;
}
})
};
// here we retrieve all child elements with a "data-category" attribute of a .row element,
// and iterate over that NodeList with NodeList.prototype.forEach():
document.querySelectorAll('.row > [data-category]').forEach(
// using an Arrow function we pass in a reference to the current Node of the NodeList,
// and use EventTarget.addEventListener() to bind the showRelevant() function (note the
// deliberate lack of parentheses) as the event-handler for the 'click' event:
(el) => el.addEventListener('click', showRelevant)
)
:root {
--h-1: 212;
--h-2: 194;
--s: 84%;
--l: 62%;
--c-l: var(--l);
--bgc-l: var(--l);
}
* {
box-sizing: border-box;
}
.row {
/* rather than using float, I've used display: flex: */
display: flex;
/* the default of flex elements is:
flex-direction: row;
flex-wrap: nowrap;
flex-flow is a shorthand to update both those values;
here I've specified:
flex-direction: row;
flex-wrap: wrap;
*/
flex-flow: row wrap;
/* adjust to taste, but this replicates the behaviour of
floating in that elements on an incomplete row will
align to the start of the row: */
justify-content: start;
/* placing a 0.2em margin on the block-axis of the element;
in a language such as English (left-to-right, top-to-bottom)
that aligns to the top (margin-block-start) and bottom
(margin-block-end) margins: */
margin-block: 0.2em;
}
.row > * {
box-shadow: inset 0 0 0 3px currentColor, inset 0 0 0 4px #fff;
/* basing the width of the elements - using the flex-basis
property - to 33%: */
flex-basis: 33%;
padding: 10px;
}
.row > *:nth-child(even) {
/* using CSS custom properties to set color and
background-color: */
color: hsl(var(--h-1) var(--s) var(--c-l));
background-color: hsl(var(--h-2) var(--s) var(--bgc-l));
}
.row > *:nth-child(odd) {
color: hsl(var(--h-2) var(--s) var(--c-l));
background-color: hsl(var(--h-1) var(--s) var(--bgc-l));
}
.row > *:nth-child(even):hover,
.row > *:nth-child(odd):hover {
/* manipulating the CSS custom properties with the
calc function to make the color darker (by decreasing
the lightness) and the background-color lighter (by
increasing the lightness): */
--c-l: calc(var(--l)*0.5);
--bgc-l: calc(var(--l) * 1.2);
}
<div class="row">
<!--main divs-->
<!-- I've added a custom data-* attribute to each of the elements that would
constitute a 'filter' element; the attribute-value is all the initial
letters of the words written as camel-case, so:
'Adventure Holidays' => 'AH' => 'aH' -->
<div id="adventureHolidays" data-category="aH">
<p>Adventure Holidays</p>
</div>
<div id="backpacking" data-category="bP">
<p>Backpacking</p>
</div>
<div id="cruiseHolidays" data-category="cH">
<p>Cruise Holidays</p>
</div>
<div id="eventTravel" data-category="eT">
<p>Event Travel</p>
</div>
<div id="packageHoliday" data-category="pH">
<p>Package Holiday</p>
</div>
<div id="safari" data-category="s">
<p>Safari</p>
</div>
<div id="skiingAndSnowboarding" data-category="sAS">
<p>Skiing and Snowboarding</p>
</div>
<div id="volunteering" data-category="v">
<p>Volunteering</p>
</div>
<div data-category="all">
<p>Show all</p>
</div>
<!--end on main divs-->
</div>
<!-- this isn't essential, but I prefer to separate the 'filters' from the elements to be filtered: -->
<div class="row">
<!--sub divs-->
<!-- I've changed the id prefix of these elements to match the 'data-category' value from the
'filter' <div> elements: -->
<div id="aH-summerCamps">
<p>Summer camps</p>
</div>
<div id="aH-trekking">
<p>Trekking</p>
</div>
<div id="bP-longDistanceHiking">
<p>Long Distance Hiking</p>
</div>
<div id="bP-thruHiking">
<p>Thru Hiking</p>
</div>
<div id="cH-oceanCruising">
<p>Ocean Cruising</p>
</div>
<div id="cH-riverCruising">
<p>River Cruising</p>
</div>
<div id="eT-recreationsEvent">
<p>Recreations Events</p>
</div>
<div id="eT-sportsEvents">
<p>Sports events</p>
</div>
<div id="pH-escortedTours">
<p>Escorted Tours</p>
</div>
<div id="pH-independentTours">
<p>Independent Tours</p>
</div>
<div id="s-photographicSafari">
<p>Photographic Safari</p>
</div>
<div id="s-cyclingSafari">
<p>Cycling Safari</p>
</div>
<div id="sAS-backcountrySkiing">
<p>Backcountry skiing</p>
</div>
<div id="sAS-downhillSkiing">
<p>Downhill skiing</p>
</div>
<div id="v-childcare">
<p>Childcare</p>
</div>
<div id="v-conservationAndEnvironment">
<p>Conservation and Environment</p>
</div>
</div>
JS Fiddle demo.
References:
Arrow functions.
data-* attributes.
document.querySelectorAll().
Event.
EventTarget.addEventListener().
HTMLElement.dataset API.
HTMLElement.hidden property.
NodeList.prototype.forEach().
String.prototype.split().
Add an id to your main div with class 'row', e.x. daDiv then iterate and perform whatever you want checking id attribute of each one
$('#daDiv').children('div').each(function () {
if ($(this).attr('id') !== 'bP-longDistanceHiking' && $(this).attr('id') !== 'bP-thruHiking') {
$(this).hide();
}
});
CodePen
Example
UPDATE
You can even make a function
function hideExcept(arr) {
$('#daDiv').children('div').each(function () {
if (!arr.includes($(this).attr('id')))
$(this).hide();
});
}
hideExcept(['bP-longDistanceHiking', 'bP-thruHiking']); // hide all except bP-longDistanceHiking and bP-thruHiking
I have three divs and I want that every single time I click on any div, it will be swapped with a second div which is meant to be at the center.
I have tried like this and it doesn't work:
function swapDiv(event, elem) {
elem.parentNode.insertBefore(elem, elem.parentNode.secondChild);
}
<div class="all-div-container">
<div class="div1" onclick="swapDiv(event,this);">
1
</div>
<div class="div2" onclick="swapDiv(event,this);">
2
</div>
<div class="div3" onclick="swapDiv(event,this);">
3
</div>
</div>
1 2 3 and when I click 3 the result must be 1 3 2 from this result and I click on 1 it's must be 3 1 2
function swapDiv(event, elem) {
// get all elements in .all-div-container
const allElements = [...elem.parentElement.children];
// get index of target elem
const targetIndex = allElements.indexOf(elem);
// get center element
const centerElem = allElements[1];
// exit from function if we clicked at center elem
if (elem === centerElem) return;
// move center element
if (targetIndex === 0) {
elem.parentElement.prepend(centerElem)
} else {
elem.parentElement.append(centerElem)
}
}
<div class="all-div-container">
<div class="div1" onclick="swapDiv(event,this);">
1
</div>
<div class="div2" onclick="swapDiv(event,this);">
2
</div>
<div class="div3" onclick="swapDiv(event,this);">
3
</div>
</div>
Consider the following.
$(function() {
$(".all-div-container > div").click(function(event) {
if ($(this).index() == 0) {
return false;
}
var $prev = $(this).prev();
var $self = $(this).detach();
$prev.before($self);
});
});
.all-div-container>div {
height: 2em;
width: 100%;
border: 1px solid #ccc;
border-radius: 3px;
margin-bottom: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all-div-container">
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</div>
You did not clarify what should happen if the first item is clicked. This code will swap the clicked element and the previous element.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
i'am trying to do a "tab" menu with only pure JS CSS and HTML, where basically i have 7 divs with content and 7 "buttons" which should open the matching div. The strategy i want to use is to put all the divs with the "hidden" or the "Display: none" attribute stacked in the same spot and then, when i click on button it turns it´s matching div to visible. The problem i am facing is how to tell the button which div it should open (using arrays instead of doing it manually), and how to set it back to invisible when i click in other div (i was thinking about an if() that just turns on the visibility if the number of the button selected matches the number of the div, but supposedly every button has a div, so i am confused).
I think you want something like this?
document.addEventListener('click', ({ target: { dataset: { id = '' }}}) => {
if (id.length > 0) {
document.querySelectorAll('.tab').forEach(t => t.classList.add('hidden'));
document.querySelector(`#${id}`).classList.remove('hidden');
}
});
.hidden {
display:none;
}
<button data-id="tab1">tab 1</button>
<button data-id="tab2">tab 2</button>
<div id="tab1" class="tab">Tab 1</div>
<div id="tab2" class="tab hidden">Tab 2</div>
But the reality is we probably don't want to actually use button.
So lets change that up.
const tabClick = ({ target }) => {
const { dataset: { id = '' }} = target;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('selected'));
target.classList.add('selected');
document.querySelectorAll('.tab-panel').forEach(t => t.classList.add('hidden'));
document.querySelector(`#${id}`).classList.remove('hidden');
};
const bindTabs = () => {
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', tabClick);
})
};
// Belts and braces, lets ensure our DOM is loaded and only assign click to the `tabs`
document.addEventListener('DOMContentLoaded', () => {
bindTabs();
});
.tab {
display: inline-block;
background-color: grey;
padding: 0.75rem;
color: #fff;
}
.selected {
background-color: black;
}
.tab-panel {
border: 2px solid black;
min-height: 50px;
max-width: 250px;
padding: 1rem;
}
.hidden {
display:none;
}
<div data-id="tab1" class="tab selected">tab 1</div>
<div data-id="tab2" class="tab">tab 2</div>
<div data-id="tab3" class="tab">tab 3</div>
<div data-id="tab4" class="tab">tab 4</div>
<div id="tab1" class="tab-panel">Tab 1</div>
<div id="tab2" class="tab-panel hidden">Tab 2</div>
<div id="tab3" class="tab-panel hidden">Tab 3</div>
<div id="tab4" class="tab-panel hidden">Tab 4</div>
So how can we approach this with basic javascript.
const tabCount = 4; // If we add a new tab, increase.
const tabClick = (event) => {
const tabButtonClicked = event.target;
const id = event.target.dataset.id;
// First remove selected and hide all tabs
for(let i = 1; i <= tabCount; i++) {
let tabButtonID = "#tabButton" + i;
let tabButton = document.querySelector(tabButtonID);
let tabID = "#" + tabButton.dataset.id;
let tab = document.querySelector(tabID);
tabButton.classList.remove("selected");
tab.classList.add("hidden");
}
// Now we set selected and show the selected tab.
document.querySelector("#" + id).classList.remove("hidden");
tabButtonClicked.classList.add("selected");
};
const bindTabs = () => {
// Loop through number of tabs and add a click event.
for(let i = 1; i <= tabCount; i++) {
let tabButtonID = "#tabButton" + i;
let tabButton = document.querySelector(tabButtonID);
tabButton.addEventListener('click', tabClick);
}
};
// Belts and braces, lets ensure our DOM is loaded and only assign click to the `tabs`
document.addEventListener('DOMContentLoaded', () => {
bindTabs();
});
.tab {
display: inline-block;
background-color: grey;
padding: 0.75rem;
color: #fff;
}
.selected {
background-color: black;
}
.tab-panel {
border: 2px solid black;
min-height: 50px;
max-width: 250px;
padding: 1rem;
}
.hidden {
display:none;
}
<div id="tabButton1" data-id="tab1" class="tab selected">tab 1</div>
<div id="tabButton2" data-id="tab2" class="tab">tab 2</div>
<div id="tabButton3" data-id="tab3" class="tab">tab 3</div>
<div id="tabButton4" data-id="tab4" class="tab">tab 4</div>
<div id="tab1" class="tab-panel">Tab 1</div>
<div id="tab2" class="tab-panel hidden">Tab 2</div>
<div id="tab3" class="tab-panel hidden">Tab 3</div>
<div id="tab4" class="tab-panel hidden">Tab 4</div>
I have data = [1,2,3,4,5,...]
Number of data can change.
Here, I have 5 data and want to create 5 divs according to the number of data(array.length) dynamically such that width of divs are adjusted in a row equally.
Using below method:-
var html="";
/*
-
-
-
*/
html +="<div</div>"
Use flex CSS display mode. If you use jQuery, it is very easy.
<div style="display: flex;" id="parent"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
var arr = [1, 2, 3, 4, 5];
for (k in arr) {
jQuery('#parent').append('<div style="flex: 1;">' + arr[k] + '</div>');
}
});
</script>
.display_flex {
display: flex; /* Important! */
}
.flex_entry {
flex: 1; /* Important! */
margin: 1px;
border: 1px solid red;
padding: 20px;
}
<div class="display_flex">
<div class="flex_entry"></div>
<div class="flex_entry"></div>
<div class="flex_entry"></div>
</div>
<div class="display_flex">
<div class="flex_entry"></div>
<div class="flex_entry"></div>
<div class="flex_entry"></div>
<div class="flex_entry"></div>
<div class="flex_entry"></div>
</div>
More about flex
Here is jsfiddle of raw code and the result should be like this
<div class="wrapper">
<div class="row">
<div class="col red">R</div>
<div class="col blue">B</div>
<div class="col green">G</div>
<div class="col orange">O</div>
</div>
</div>
The mission is: Last color of previous row should be the first in next row and first color from previuos row should be the second in next row.
I think that I have to use loop and recursion but I don't have enough knowledge to do this.
Thanks in advance :)
You can run through the for loop and do something like this
check this snippet
//last color of previous row should be first in next row
//first color from previous row should be second in next row
var colors = ['red', 'blue', 'green', 'orange'];
$(document).ready(function() {
var rows = $('.row');
rows.each(function(row) {
var index = $(this).index();
var prevRow;
if (index > 0)
prevRow = $(this).prev();
colorColumns($(this).find('.col'), prevRow);
});
});
function colorColumns(cols, prevRow) {
var index = 0;
// alert("hi");
cols.each(function(col) {
var colIndex = $(this).index();
if (prevRow) {
var cols = prevRow.find('.col').length;
var totalCols = cols - 1;
var currentIndex = ((colIndex + totalCols) % cols);
var prevRowColor = $(prevRow).find('.col').eq(currentIndex);
var classes = prevRowColor.attr('class');
var classArr = classes.split(" ");
$(this).addClass(classArr[1]);
} else {
$(this).addClass(colors[colIndex]);
}
});
}
.row {
display: flex;
}
.row .col {
width: 20px;
height: 20px;
border-radius: 100%;
text-align: center;
}
.red {
background: red;
}
.orange {
background: orange;
}
.blue {
background: blue;
}
.green {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">O</div>
</div>
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">О</div>
</div>
<div class="row">
<div class="col">R</div>
<div class="col">B</div>
<div class="col">G</div>
<div class="col">O</div>
</div>
Hope it helps