Hey everyone,
I'm having some trouble with my jQuery code and I can't seem to figure out what's going on.
Here's the scenario:
I'm creating a few divs (based on entries from MySQL) and I'd like to show you the end result:
<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, there is a ship container div with two child divs (timeline container and travels all). The travels all div in this example contains only one travel container, but there will be more in the future.
This piece of code gets repeated multiple times (I currently have two ship containers).
My goal was to set the width of the div with the class ".travelcontainer" to the sum of the widths of the four divs with the class ".travelfase". Here's 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;
});
Since I assigned a data-travelid attribute to each ".travelcontainer" during PHP parsing and also to its grandchildren with the class ".travelfase", I thought this would work.
The issue I'm facing is that when I have two ship containers, it adds up all the values together. So, the travel container with data-travelid=1 ends up with the same width as all divs with the class "travelfase," instead of just those with the data-fasetravelid=1 attribute.
I also tried this code which I used before:
var widthTotal = 0;
$(".travelcontainer").width(function () {
$(".travelcontainer > .travelfase").each(function (index, element) {
widthTotal = $(this).innerWidth() + widthTotal;
});
});
return widthTotal;
Unfortunately, this has the same effect.
If anyone can spot what I'm doing wrong, I would really appreciate your help!
Thanks in advance!