I am creating <section>
dynamically through a template by using Backbone.js, underscore.js, jQuery, .CSS, and HTML.
What I would like it to do is whenever a user types a value or uses the slider, information gets stored with backbone.js and then get loaded with the template below. <section>
will be created with the specified height. That be said, I need to assume each <section>
has different heights regardless of the content.
This is a screenshot of what I currently have with all sections having the same height
This is the template:
<script type="text/template" id="section-template">
<section class="view">
<label><%- height %></label>
<label><%- color %></label>
</section>
</script>
I have tried this in jQuery but obviously it did not work because this applies to all <section>
.
CSS:
section {
height: 200px;
}
jQuery:
$( "#slider" ).slider({
range: "max",
min: 50,
max: 500,
value: 300,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
$('section').css('height', ui.value);
}
});
My question is what is the best technique in creating <section>
dynamically with different heights? Preferably not needing to use any plugins.
Thank you in advance.
I have been working on this and looking for alternatives today. However, after talking to a coworker, we have finally found a solution to my question. Here I will not explain how Model, View, and Collection will work together but simply a technique/trick to dynamically create section tags in .CSS so that each <section>
can have a different height.
First, I create a unique numerical id by having a global variable in JavaScript:
var counter = 0;
Whenever a user inputs a value to specify a new <section>
height, the variable increases by 1 and then create a model in a function inside Backbone.View.extend()
:
counter++; //1
Sections.create({height: h, id: counter}); //create a model in Collection with the attributes where h = 500 and counter = 1 in this case
I then write to .CSS to specify the height for this model or id='1'
in this case:
$('#section-'+counter).css('height', h);
Which gives me this in .CSS when a model is created:
#section-1 {
height: 500;
}
Now to the template I add id=section-<%- id %>
inside <section>
:
<script type="text/template" id="section-template">
<section class="view" id=section-<%- id %>>
<label><%- height %></label>
</section>
</script>
As you may have guessed, id: counter
will be loaded into the template every time a model is created, giving it a unique id.
It would look like this where height = 500 and id = 1:
<section class="view" id="section-1">
<label>500</label>
</section>
So when the next model (or <section>
) is created where height = 1020 and id = 2, it would look like this:
<section class="view" id="section-2">
<label>1020</label>
</section>
You can imagine now each <section>
has its own height on HTML because it has a dedicated id tag and will only call the same id tag in .CSS.
I hope this helps.