iterate over json object duplicates in handlebars - javascript

I have the following JSON Object in my javascript:
var source = $("#template").html();
var template = Handlebars.compile(source);
var igListOrig = [
{
"IG":"Problem Solving",
"AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
"SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8",
"Purpose": "Students must be able to reason, problem solve, communicate and make real life decisions that require mathematical thinking. Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",
"IP":"Problem of the Week(PoW)",
"What": "PoWs are complex problems.",
"When": "PoWs should be administered once per month.",
"How": "1.Introduce problem, process, and rubric. 2.Students are given time in class to work on problem throughout the week. 3.Students complete write up. 4.Student peer edit write up. 5.Students revise write up"
},
{
"IG":"Problem Solving",
"AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
"SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8",
"Purpose": "Students must be able to reason, problem solve, communicate and make real life decisions that require mathematical thinking. Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",
"IP":"Problem of the Month (POM)",
"What": "The POMs are divided into five levels. Students are asked to explain their solutions and reasoning in a write up.",
"When": "Students should work on problem the first 10-15 minutes of a period for 5-7 consecutive days. ",
"How": "Write them on a pieces of paper."
},
{
"IG":"Problem Solving",
"AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
"SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8",
"Purpose": "Students must be able to reason, problem solve, communicate and make real life decisions that require mathematical thinking. Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",
"IP":"Formative Assessment Lesson (FAL)",
"What": "FALs consist of 3 parts including a pre-assessment (approximately 15 min.",
"When": "The 3 part cycle is intended to be given approximately two-thirds the way into a unit of study.",
"How": "1.Pre assessment. 2.Introduce activity. 3.Students work collaboratively. 4.Whole class discussion/ presentation. 5.Post assessment."
},
{
"IG":"Problem Solving", "AIR_Indicators": "All Domain 1 Indicators* 3.1, 3.2, 3.3, 3.4",
"SMP": "SMP 1, 2, 3, 4, 5, 6, 7, and 8",
"Purpose": "Students must be able to reason, problem solve, communicate and make real life decisions that require mathematical thinking. Teaching students problem solving skills and giving them opportunities to apply their skills is critical to developing their capacity to solve mathematical problems that arise in all our lives (e.g. starting a small business, figuring out the area of a room in order to purchase the correct amount of paint, filling out a tax return, tracking and setting goals for investments, etc.)",
"IP":"Mathematics Assessment Resources (MARS)",
"What": "Story Problems.",
"When": "Done at the begining of the unit.",
"How": "After each asssessment." }
]
$('body').append(template(igListOrig));
And I want to iterate over this object so only when it iterates over the 2nd, 3rd, and 4th object I get a different "IP", "What", "When", and "How" each time AND ignore all the duplicities. After each of the iterations only the "IP", "What", "When", and "How" are different. I need to keep these differences and ignore other other duplicates.
I referenced something like this but I think this person's situation was a little different.
Iterating over a JSON-Object
Eventually this will go in a handlebars template like this
<script id="template" type="text/x-handlebars-template">
<div class="container">
{{#each this }}
<div class='titles'>
<div class="left">Aspire Logo</div>
<div class="middle">{{IG}}</div>
<div class="right">Common Core</div>
<div class="purple"></div>
</div>
<div class="split">
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">AIR</span> Indicators:
</p>
<ul>
<li>{{AIR_Indicators}}</li>
</ul>
</div>
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
</p>
<ul>
<li>{{SMP}}</li>
</ul>
</div>
</div>
<div class="purpose heading">
<h3>Purpose</h3>
</div>
<div class="purpose text">
<p>
{{Purpose}}
</p>
</div>
<div class="process heading">
<h3> Process </h3>
</div>
<div class="bottom-container text">
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3> {{IP}} </h3> </center> </br>
<p><span class="description">What</span> {{What}} </p></br>
<p><span class="description">When</span> {{When}} </p></br>
<p><span class="description">How</span> {{How}} </p></br>
</div>
</div>
{{/each}}
</div>
</script>
Eventually, the "IP", "What", "When", and "How" will look something like this near the bottom half of the document under the heading "Process"
http://imgur.com/rV4PIFC
Here is the JS Fiddle I'm working with:
http://jsfiddle.net/rr9Vz/
UPDATE
I just tried something like this
var ips = [];
for(var i in igListOrig) {
var ip = igListOrig[i].IP + igListOrig[i].What + igListOrig[i].When +
igListOrig[i].How ;
if($.inArray(ip,ips)== -1 ){
ips.push(ip);
}
}
And I get the array that I need, but now how do I pass my templating AND this iteration through in handlebars?
UPDATE 2
For all intents and purposes the <div class='bottom-container text> needs to look like this when Handlebars compiles.
<script id="template" type="text/x-handlebars-template">
<div class="container">
<div class='titles'>
<div class="left">Aspire Logo</div>
<div class="middle">{{IG}}</div>
<div class="right">Common Core</div>
<div class="purple"></div>
</div>
<div class="split">
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">AIR</span> Indicators:
</p>
<ul>
<li>{{AIR_Indicators}}</li>
</ul>
</div>
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
</p>
<ul>
<li>{{SMP}}</li>
</ul>
</div>
</div>
<div class="purpose heading">
<h3>Purpose</h3>
</div>
<div class="purpose text">
<p>
{{Purpose}}
</p>
</div>
<div class="process heading">
<h3> Process </h3>
</div>
<div class="bottom-container text">
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3> Problem Solving</h3> </center> </br>
<p><span class="description">What</span> PoWs are complex problems. </p></br>
<p><span class="description">When</span> PoWs should be administered once per month. </p></br>
<p><span class="description">How</span> 1.Introduce problem, process, and rubric. 2.Students are given time in class to work on problem throughout the week. 3.Students complete write up. 4.Student peer edit write up. 5.Students revise write up</p></br>
</div>
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3> Problem of the Month (POM) </h3> </center> </br>
<p><span class="description">What</span> The POMs are divided into five levels. Students are asked to explain their solutions and reasoning in a write up. </p></br>
<p><span class="description">When</span> Students should work on problem the first 10-15 minutes of a period for 5-7 consecutive days. </p></br>
<p><span class="description">How</span> Write them on a pieces of paper. </p></br>
</div>
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3> Formative Assessment Lesson (FAL) </h3> </center> </br>
<p><span class="description">What</span> FALs consist of 3 parts including a pre-assessment (approximately 15 min. </p></br>
<p><span class="description">When</span> The 3 part cycle is intended to be given approximately two-thirds the way into a unit of study. </p></br>
<p><span class="description">How</span> 1.Pre assessment. 2.Introduce activity. 3.Students work collaboratively. 4.Whole class discussion/ presentation. 5.Post assessment. </p></br>
</div>
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3> Mathematics Assessment Resources (MARS)</h3> </center> </br>
<p><span class="description">What</span> Story Problems. </p></br>
<p><span class="description">When</span> Done at the begining of the unit. </p></br>
<p><span class="description">How</span> After each asssessment. </p></br>
</div>
</div>
</div>
I want this: http://jsfiddle.net/8Xnpk/1/
but I'm getting this: http://jsfiddle.net/rr9Vz/3/
#MarcoCl's solution works in terms of code execution, but for whatever eason I can't seem to get this http://jsfiddle.net/8Xnpk/1/

In order to avoid duplicates, use a dictionary instead of an array: this speed up the duplicate lookup and it won't hurt your current code.
function filterDuplicates(array){
// this will hold the new filtered dictionary
var uniqArray = [],
// this is used for the lookup
dupCheck = {};
for( var i=0; i< array.length; i++){
var entry = array[i];
var uniqueKey = entry.IP + entry.What + entry.When + entry.How;
if(!dupCheck[uniqueKey]){
// here there are only unique values
dupCheck[uniqueKey] = true;
uniqArray.push(entry);
}
}
return uniqArray;
}
var source = $("#template").html();
var template = Handlebars.compile(source);
var igListOrig = [...];
$('body').append(template(filterDuplicates(igListOrig)));
As alternative you can integrate the filterDuplicates logic in a custom Handlebar helper.
Replace the {{#each this}} tag with the custom {{€#eachUnique this}} one:
<script id="template" type="text/x-handlebars-template">
<div class="container">
{{#eachUnique this}}
...
{{/eachUnique}}
</div>
</script>
Then register the new helper:
Handlebars.registerHelper('eachUnique', function(array, options) {
// this is used for the lookup
var dupCheck = {};
// template buffer
var buffer = '';
for( var i=0; i< array.length; i++){
var entry = array[i];
var uniqueKey = entry.IP + entry.What + entry.When + entry.How;
// check if the entry has been added already
if(!dupCheck[uniqueKey]){
// here there are only unique values
dupCheck[uniqueKey] = true;
// add this in the template
buffer += options.fn(entry);
}
}
// return the template compiled
return buffer;
});
Update 2
The problem changed a bit from the original one - it was only about removing duplicates from a list and it became a more template-related question...
I'll leave the duplicate answer and add this other one for the second update:
Preprocess your data to remove the common data:
var source = $("#template").html();
var template = Handlebars.compile(source);
var igListOrig = [...];
var newModel = {
'IG': igListOrig[0].IG,
'AIR_Indicators': igListOrig[0].AIR_Indicators,
'SMP': igListOrig[0].SMP,
'Purpose':igListOrig[0].Purpose ,
entries: igListOrig
};
$('body').append(template(newModel));
The new template will look like this one:
<script id="template" type="text/x-handlebars-template">
<div class="container">
<div class='titles'>
<div class="left">Aspire Logo</div>
<div class="middle">{{IG}}</div>
<div class="right">Common Core</div>
<div class="purple"></div>
</div>
<div class="split">
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">AIR</span> Indicators:
</p>
<ul>
<li>{{AIR_Indicators}}</li>
</ul>
</div>
<div class="text">
<p class="split-heading">
Aligned to the following <span class="bold">Standards of Mathematical Practice:</span>
</p>
<ul>
<li>{{SMP}}</li>
</ul>
</div>
</div>
<div class="purpose heading">
<h3>Purpose</h3>
</div>
<div class="purpose text">
<p>
{{Purpose}}
</p>
</div>
<div class="process heading">
<h3> Process </h3>
</div>
<div class="bottom-container text">
// use eachUnique here instead of each to avoid duplicates
{{eachUnique items}}
<div class="cube">
<h4>Instructional Practice</h4>
<center><h3>{{IP}}</h3> </center> </br>
<p><span class="description">What</span> {{What}} </p></br>
<p><span class="description">When</span> {{When}}</p></br>
<p><span class="description">How</span> {{How}}</p></br>
</div>
{{/eachUnique}}
</div>
</div>
</script>

Related

Text not fully redrawing when I toggle between templates

On my AngularJS app I have a view that allows me to toggle between type of insurance cover and it works fine. However on iPhone in particular (Chrome & Safari), the text kind of scrambles when I toggle between the prices. To be very clear about it, it's only the top few pixels and those pixels generally belong to the price toggled away from, so it's like the page isn't properly redrawing it. This issue then goes away if I do anything in the Dev tools. Any help is appreciated here.
EDIT: This appears to only happen when I select an option that updates the value displayed, not when it switched to a different piece of template.
Here's a screenshot
And a slightly stripped down version of the template in question:
<div class="row quote-tab-container">
<div class="col">
<div class="quote__tab">
<button ng-click="selectedCoverType = 'Comp'; setCoverDetails()" class="quote__tab__button">
Comprehensive
<div class="active-selection" ng-show="selectedCoverType === 'Comp'"></div>
</button>
<button ng-click="selectedCoverType = 'Tpft'; setCoverDetails()" class="quote__tab__button">
Third Party,<br />Fire & Theft
<div class="active-selection-tpft" ng-show="selectedCoverType === 'Tpft'"></div>
</button>
</div>
</div>
</div>
<div class="quote-details row">
<div class="col">
<div class="answer--radio">
<input ng-click="paymentType = 'CC'" type="radio" ng-checked="paymentType == 'CC'" id="singlePayment" name="payment-type">
<label for="singlePayment">Single Payment</label>
</div>
<div class="answer--radio answer--radio--right">
<input ng-click="paymentType = 'DD'" type="radio" ng-checked="paymentType == 'DD'" id="monthlyPayments" name="payment-type">
<label for="monthlyPayments">Monthly Payments</label>
</div>
<section class="selected-product answer--checkbox" ng-show="paymentType == 'CC'">
<div class="your-online-price">
Your online price is
</div>
<div class="selected-product__price">
{{totalPremium | signedCurrencyFilter}}
</div>
<div class="selected-product__includes">
Price includes online discount of {{onlineDiscount | signedCurrencyFilter}}
</div>
</section>
<section class="selected-product answer--checkbox" ng-show="paymentType == 'DD'">
<div class="your-online-price">
Your online price is
</div>
<div class="selected-product__price">
{{instalmentAmount | signedCurrencyFilter}}
</div>
<div class="selected-product__includes">
Price includes online discount of {{onlineDiscount | signedCurrencyFilter}}
</div>
</section>
</div>
</div>
So because the browser would correct this glitch whenever the screen resized or had to redraw I had to force a redraw any time these options were selected. The best way to do this seemed to be to clone the element and replace the original with the clone in order to force a redraw, this was enclosed in a timeout in order to send this to the end of the execution queue.
This answer helped with this: https://stackoverflow.com/a/8840703/1999035
var n = document.createTextNode(' ');
var opacity = element.style.opacity;
element.appendChild(n);
element.style.opacity = '0.5';
setTimeout(function(){
element.style.display = opacity;
n.parentNode.removeChild(n);
}, 20);
My edit of the proposed solution is to use the opacity property rather than display, because the display change causes a jitter/glitch/flash that looks really bad.Opacity just causes a slight fade.

Add Autoplay to this JS Slider

I've implemented this cool 3d slider but don't know how to add autoplay to cycle through the slides. Any suggestions? Here is the link to the codepen below. I've included some of the HTML snippets but not the any of the CSS or javascript because I couldn't get it to format properly.
https://codepen.io/paulnoble/pen/yVyQxv
<div class="carousel">
<div class="carousel__control">
</div>
<div class="carousel__stage">
<div class="spinner spinner--left">
<div class="spinner__face js-active" data-bg="#27323c">
<div class="content" data-type="iceland">
<div class="content__left">
<h1>ICELAND<br><span>EUROPE</span></h1>
</div>
<div class="content__right">
<div class="content__main">
<p>“As I flew north to begin my third circuit of Iceland in four years, I was slightly anxious. The number of visitors to Iceland has doubled in that period, and I feared this might mean a little less magic to go around. At the end of this trip, 6000km later, I'm thrilled to report that the magic levels remain high. It's found in glorious football victories and Viking chants, kayaking among icebergs, sitting with puffins under the midnight sun and crunching across brand-new lava fields.” </p>
<p>– Carolyn Bain</p>
</div>
<h3 class="content__index">01</h3>
</div>
</div>
</div>
<div class="spinner__face" data-bg="#19304a">
<div class="content" data-type="china">
<div class="content__left">
<h1>CHINA<br><span>ASIA</span></h1>
</div>
<div class="content__right">
<div class="content__main">
<p>“Its modern face is dazzling, but China is no one-trick pony. The world's oldest continuous civilisation isn't all smoked glass and brushed aluminium and while you won't be tripping over artefacts – three decades of round-the-clock development and rash town-planning have taken their toll – rich seams of antiquity await.”</p>
<p>– Damian Harper</p>
</div>
<h3 class="content__index">02</h3>
</div>
</div>
</div>
<div class="spinner__face" data-bg="#2b2533">
<div class="content" data-type="usa">
<div class="content__left">
<h1>USA<br><span>NORTH AMERICA</span></h1>
</div>
<div class="content__right">
<div class="content__main">
<p>“When it comes to travel, America has always floored me with its staggering range of possibilities. Not many other countries have so much natural beauty – mountains, beaches, rainforest, deserts, canyons, glaciers – coupled with fascinating cities to explore, an unrivaled music scene and all the things that make travel so rewarding (friendly locals, great restaurants and farmers markets, and plenty of quirky surprises).” </p>
<p>– Regis St Louis</p>
</div>
<h3 class="content__index">03</h3>
</div>
</div>
</div>
</div>
This will enable autoplay but also allow you to jump indexes and continue autoplay from that whatever index you're on
const autoplay = () => {
const max = $controls.length;
setInterval(() => {
// use the internal activeIndex to track
$controls.eq(activeIndex).next().click();
if(activeIndex + 1 === max){
$controls.eq(0).click();
}
}, 3000);
}
const init = () => {
assignEls()
prepareDom()
attachListeners()
autoplay()
}
DEMO
Just call the spin() function inside an interval.
setInterval(spin, 3000);
Place this after the call to init() at the bottom of the code on CodePen.

jQuery minify duplication

I have a working jsFiddle that shows content based on drop-down value. How can I minify the jQuery so that I don't have to repeat myself for each 'port'. At the moment I have done 2 'ports' but it will take a while to populate the remainder.
http://jsfiddle.net/d4pvz51v/1/
$(document).ready(function () {
$("select").change(function () {
$("select option:selected").each(function () {
if ($(this).attr("value") == "all") {
$(".auckland").hide();
$(".tauranga").hide();
$(".all").show();
}
if ($(this).attr("value") == "auckland") {
$(".all").hide();
$(".auckland").show();
$(".tauranga").hide();
}
if ($(this).attr("value") == "tauranga") {
$(".all").hide();
$(".auckland").hide();
$(".tauranga").show();
}
});
}).change();
$('.auckland-link').click(function () {
$('select option:contains("Auckland")').prop('selected', true);
$('.auckland').show();
$('.tauranga').hide();
$(".all").hide();
});
$('.tauranga-link').click(function () {
$('select option:contains("Tauranga")').prop('selected', true);
$('.auckland').hide();
$('.tauranga').show();
$(".all").hide();
});
});
Instead of adding different handlers for each option or link you can
On change of the select, hide all elements with class data, then show the element with the class as the selected value
In the same way you can have a single click handler for the links, assign a common class to all of the link elements then add an data-*(data-el in this case) to specify the target elements class name. In its click handler read the data value and set it as the select element's value and then manually trigger the select's change handler which will set the proper data element visibility.
$(document).ready(function() {
$("select").change(function() {
var $target = $('.' + $(this).val()).show();
$('.data').not($target).hide();
}).change();
$('.data-link').click(function() {
var val = $(this).data('el')
$('select').val(val).change();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section class="ports section-padding text-center" id="ports">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>PORTS OF OPERATION</h1>
<h3>Select a port to view information and contact details</h3>
<select class="choose">
<option value="all">Select Port</option>
<option value="auckland">Port of Auckland</option>
<option value="tauranga">Port of Tauranga</option>
</select>
</div>
</div>
</div>
</section>
<section class="all data section-padding">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<h2>Port of Whangarei</h2>
<hr />
<h2 class="data-link" data-el="auckland">Port of Auckland</h2>
<hr />
<h2 class="data-link" data-el="tauranga">Port of Tauranga</h2>
<hr />
<h2>Eastland Port</h2>
<hr />
<h2>Port Taranaki</h2>
<hr />
</div>
<div class="col-md-4">
<h2>Port of Napier</h2>
<hr />
<h2>Port Nelson</h2>
<hr />
<h2>Centre Port Wellington</h2>
<hr />
<h2>Port Malborough</h2>
<hr />
<h2>Greymouth Port</h2>
<hr />
</div>
<div class="col-md-4">
<h2>Lyttleton Port</h2>
<hr />
<h2>Primeport Tmaru</h2>
<hr />
<h2>Port Otago</h2>
<hr />
<h2>Southport</h2>
<hr />
</div>
</div>
</div>
</div>
</section>
<section class="auckland data section-padding">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<h2>Port Information</h2>
<p>Port of Auckland is centrally located on the west coast of the North Island and is one of New Zealand 's key import and export ports.</p>
<p>Port of Auckland offers nine fully serviced berths for a wide variety of cargoes and vessels. The maximum port draft is 12.5m, and for vessels in excess of 10m Dynamic Under Keel Clearance (DUKC) must be used.</p>
<p>Port of Auckland has the ability to handle a wide diversity of cargoes including all forms of bulk products (liquid and dry), containerised, and break-bulk products (general, refrigerated or palletised), and has specialist experience in the
handling of heavy lift and project cargoes. All wharves are supported by covered and open storage areas.</p>
</div>
<div class="col-md-4">
<h2>Features</h2>
<p>An unusual feature of the port is that it has a beach within its breakwaters adjacent to its operational area. The popularity of Ngamotu Beach is testament to Port Taranaki's commitment to safe working practices and regard for the environment.</p>
<p>Another special feature of Port of Auckland is its "heavy lift" expertise. Auckland has a sophisticated engineering infrastructure, which evolved primarily as a result of development of the region's oil and gas industries. As the petrochemical
industries grew many oversized and heavy cargoes were imported and exported through Port Taranaki. Specialist know-how and facilities are available through Port of Auckland for the handling of extra heavy lifts.</p>
</div>
<div class="col-md-4">
<hr />
<img style="padding-top:40px;float:right;" src="img/map-taranaki.png" alt="" />
</div>
</div>
</div>
</div>
</section>
<section class="tauranga data section-padding">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<h2>Port Tauranga</h2>
<p>Port of Auckland is centrally located on the west coast of the North Island and is one of New Zealand 's key import and export ports.</p>
<p>Port of Auckland offers nine fully serviced berths for a wide variety of cargoes and vessels. The maximum port draft is 12.5m, and for vessels in excess of 10m Dynamic Under Keel Clearance (DUKC) must be used.</p>
<p>Port of Auckland has the ability to handle a wide diversity of cargoes including all forms of bulk products (liquid and dry), containerised, and break-bulk products (general, refrigerated or palletised), and has specialist experience in the
handling of heavy lift and project cargoes. All wharves are supported by covered and open storage areas.</p>
</div>
<div class="col-md-4">
<h2>Features</h2>
<p>An unusual feature of the port is that it has a beach within its breakwaters adjacent to its operational area. The popularity of Ngamotu Beach is testament to Port Taranaki's commitment to safe working practices and regard for the environment.</p>
<p>Another special feature of Port of Auckland is its "heavy lift" expertise. Auckland has a sophisticated engineering infrastructure, which evolved primarily as a result of development of the region's oil and gas industries. As the petrochemical
industries grew many oversized and heavy cargoes were imported and exported through Port Taranaki. Specialist know-how and facilities are available through Port of Auckland for the handling of extra heavy lifts.</p>
</div>
<div class="col-md-4">
<hr />
<img style="padding-top:40px;float:right;" src="img/map-taranaki.png" alt="" />
</div>
</div>
</div>
</div>
</section>
function manageState(hide1,hide2,show){
$(hide1).hide();
$(show).show();
$(hide2).hide();
}
Make a method that takes in two fields to hide and one to show. Pass in the specific classes for each condition. This works since you seem to be hiding in paris and showing a single item.
Example:
manageState('.all','.auckland','.tauranga')

How to create an array of divs with content?

I'm trying to create an array of nested divs, in which I only need to change 3 values when writing the divs to the document (html).
My divs look like this:
<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>
I need to create an array of about 50 items, and then use the document.write function to write 4 of those arrays for each page, as a section for "similar stuff".
I searched on stackoverflow, and came up with :: this page :: , which explains how to create an array in javascript, and then found another script that uses the document.write function.
The script uses an array of categories, to populate a form selection. And it does so, but using an array : (var categories = new Array("a1", "a2", "a3", ...) and so on.
for(var hi=0; hi<categories.length; hi++)
document.write("<option value=\""+categories[hi]+"\">"+categories[hi]+"</option>");
Could I use these two scripts to populate a section with 4 items from the array of the divs?
If so, then how could I do it? I know it can be done in php, but don't know if this can be done in javascript.
I tried, and created this array in notepad++, but the code wasn't recognized as a string, per array element...
var array_divs = [
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 1</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>') ,
$('<div class="item">
<div class="item-h"> <a class="item-anchor" href="1_water_bottle_2.html">
<div class="item-image"> <img class="item-image-first" src="images/img_1_water_bottle_2.png" alt="">
<div class="item-meta">
<h2 class="title">Water Bottle 2</h2>
<span class="item-arrow"></span> </div>
</div>
</a> </div>
</div>')
]
Trying to populate the section, with selective items from the array, for example:
document.write(array_divs[1],array_divs[2]);
I haven't tried this, but since notepad++ didn't treat my div as a string, I had to search again... but couldn't find any info regarding this.
Thanks for any help.
-

How to use nested for loops to create FAQ?

I am creating a list of frequently asked question with questions and explanations. By default i want to show questions only.
If a user clicks on a particular question, then only its answer should expand, closing all the other answers.
I'm using nested loops.
<html>
<head>
<title></title>
</head>
<script>
function display(k){
for(i=1;i<=k;i++){
for(j=i; j<=i; j++){
document.getElementById('sol'+j).style.display="block";
}
document.getElementById('sol'+i).style.display="none";
}
}
</script>
<body>
<div id="faq1" onclick="display(1)">FAQ 1: Return Policy
<div id="sol1" style="display: none;">
Customer can replace products within 30 days from the days of purchase.
</div>
</div>
<div id="faq2" onclick="display(2)">FAQ 2: Warranty
<div id="sol2" style="display: none;">
Warranty would be solely fulfiled by the brand company.
</div>
</div>
<div id="faq3" onclick="display(3)">FAQ 3: Extended Warranty
<div id="sol3" style="display: none;">
Customer can apply for extended warranty for their products provided their products fulfil the TOS.
</div>
</div>
<div id="faq4" onclick="display(4)">FAQ 4: Address
<div id="sol4" style="display: none;">
Our company is situated in the heart of the city Jammu.
</div>
</div>
</body>
</html>
i tried different combinations, but i'm stuck.
A much easier approach would be to add a CSS class for all the questions and for all the answers.
Then specify, for example let's use .answer, that the class elements are hidden (.answer {display: none}). Then, use JS to create an event listener for all the question class elements, and upon clicking just toggle it's child div (.answer).
That way you'd avoid many errors and bad design choices you have in your code, like: repeated ids, inline styles, separate onclick attributes for every question div, etc.
Add jquery and make it simple.
jsFiddle
<script type="text/javascript">
$(document).ready(function(){
$('.faq').click(function(){
if($(this).find('div:first-child').is(':visible'))
$(this).find('div:first-child').hide('slow');
else
{
$('.faq').children().hide('slow');
$(this).find('div:first-child').show('slow');
}
});
});
</script>
try using document.getElementsByClassName : see this DEMO
function display(k){
arr = document.getElementsByClassName('sol');
for(i=0; i<arr.length; i++){
arr[i].style.display="none";
}
document.getElementById('sol'+k).style.display="block";
}
css:
.sol{
display: none;
}
and add class sol to divs:
<div id="sol1" class="sol">
Customer can replace products within 30 days from the days of purchase.
</div>
HTML is here
<div id="faq1" class="faqcls">FAQ 1: Return Policy
<div id="sol1" class="solcls" style="display: none;">
Customer can replace products within 30 days from the days of purchase.
</div>
</div>
<div id="faq2" class="faqcls" >FAQ 2: Warranty
<div id="sol2" class="solcls" style="display: none;">
Warranty would be solely fulfiled by the brand company.
</div>
</div>
<div id="faq3" class="solcls" class="faqcls">FAQ 3: Extended Warranty
<div id="sol3" style="display: none;">
Customer can apply for extended warranty for their products provided their products fulfil the TOS.
</div>
</div>
<div id="faq4" class="solcls" class="faqcls">FAQ 4: Address
<div id="sol4" style="display: none;">
Our company is situated in the heart of the city Jammu.
</div>
</div>
and javascript is here
$(document).on('click','.faqcls',function() {
$(this).find('.solcls').slideToggle();
});
and jsfiddle is http://jsfiddle.net/A3Pwg/

Categories

Resources