Good afternoon fellows,
I’m having trouble with some jQuery-code and I can’t seem to grasp the problem.
The situation is as follows:
I’m making (based on mysql-entries) a couple of div’s. Perhaps it’s better if I show you the result first:
<div class="shipcontainer" id="shipcontainer1">
<div class="timelinecontainer" id="timelinecontainer1">timeline--></div>
<div class="travelsall" data-ship="1">
<div class="travelcontainer" data-travelid="1" data-ship="1" id="travelcontainer1">
<div class="fasecontainer" data-travelid="1" data-ship="1">
<div class="Mobilize travelfase" date-days="6" date-fasetravelid="1">1: Mobilize </div>
<div class="Loading travelfase" date-days="12" date-fasetravelid="1">2: Loading</div>
<div class="Boating travelfase" date-days="20" date-fasetravelid="1">3: Boating</div>
<div class="Discharge travelfase" date-days="6" date-fasetravelid="1">4: Discharge</div>
</div>
<div class="options" id="optionstravel1" data-travelid="1">OPTIONS</div>
</div>
</div>
</div>
As you can see, I have a shipcontainerdiv. Within i have two child-divs (timelinecontainer and travelsall). The latter contains in this example only one “.travelcontainer”, but there will be more in the future.
This piece of code is repeated a couple of times, (I currently have two “.shipcontainers”).
What I wanted to achieve was to set the width of the div with “.travelcontainer” to the sum of the widths of the four div’s with “.travelfase”. This is my jQuery code:
var totalWidth = 0;
$(".travelcontainer").width(function () {
var travelID = $(this).data(travelid);
$(this).find('div[data-fasetravelid=' + travelID + ']').each(function (index, element) {
totalWidth = $(this).innerWidth() + totalWidth;
});
return totalWidth;
});
Because, during it’s parsing through PHP, I gave the “.travelcontainer” a data-travelid attribute, and also it’s “.travelfase” grandchildren. I figured I could couple them together this way.
The problem is that when I have 2 shipcontainers, with both a “travelcontainer” it’s adding all values together. So travelcontainer with data-travelid=1, has the width of exactly the same as all div’s with class travelfase, instead of only the div’s with the data-fasetravelid=1 attribute.
I’ve also tried this code (which I’ve used earlier):
var widthTotal = 0;
$(".travelcontainer").width(function () {
$(".travelcontainer > .travelfase").each(function (index, element) {
widthTotal = $(this).innerWidth() + widthTotal;
});
});
return widthTotal;
This also has the same effect.
Does anyone see what I’m doing wrong here?
Thanks in advance!
Try: