0

I'm making some kind of movie with a webpage. For that I have to do certain things with the chars of the text. The html looks like this:

<div id="section_1" style="display: none;">
        <p>Goede typografie stimuleert het lezen en heeft als gevolg dat men zo weinig mogelijk moeite hoeft te doen om  een tekst te kunnen lezen. Het moet zo min mogelijk weerstand oproepen om een tekst te kunnen begrijpen.</p>
</div>

<div id="section_2" style="display: none;">
    <p>Het vermogen om zeer snel te kunnen lezen en zodoende onze tijd effectief te kunnen gebruiken, hangt vooral af van de wijze waarop de boodschap typografisch is vormgegeven.</p>
</div>

To use the chars, I span every letter. Shown below:

var spans = new Array();


// span every character
for(var i = 0; i < data.sections.length; i++) {
    //spanEachChar("#section_"+i);
    $("#section_"+i).children().andSelf().contents().each(function(index){
    if (this.nodeType == 3) {
        var $this = $(this);
        $this.replaceWith($this.text().replace(/\w/g, function(text,index2) {
            return "<span id="+index2+">" + text + "</span>";
        }));
    }
    });
}

// store each span in an array
$("#content span").each(function() {
    spans.push($(this));
});

console.log("spans.length "+spans.length);

// get them like this
var span = spans[20];

I also have a array/object (don't know what it's called) where I store the duration for each section so it shows the new one after a certain time.

  var data = {
            sections:[{
                id: 0,
                duration: 0,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }, {
                id: 1,
                duration: 7,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }, {
                id: 2,
                duration: 7,
                firstSpanIndex: -1,
                lastSpanIndex: -1
            }]
    }

There is the array named spans, shown above, for each div for example in 'section_2', I want to store the firstSpanIndex and the last lastSpanIndex. I think this maybe can be done at the part where I span every character but i wouldn't know how. I hope you guys understand my question, it's not that easy to explain.


update

Thanks for the help so far. It's helpfull for the purpose of learning but not really what i wanted. I made a image to make more clear what i want.

example of what i want

I hope the image is clear enough. It shows 4 paragraps split up in spans for each char. All those spans are in one array. Nothing more in that array (so no first or last). Then the data.sections hold's info for each paragraph, like the id (equal to the index atm) and how many seconds it should show up (not show in the image) and the start and end index of the span array.

4 Answers 4

2

Would jQuery's .first() and .last() functions work to do what you want? For example, can you say;

// Grabs the first span only, then it's index value
firstSpanIndex: $this.children("span").first().index();

UPDATED BELOW *UPDATED AGAIN, Fiddle moved as well*

Still not sure what exactly you want to do, but i made a quick fiddle that I think demonstrates what you are trying to do. -> my jsFiddle MOVED!!! HERE!!!

I rewrote your code a bit and changed each section to contain a class called section. I did this because it appeared your sections would be known by the html but not necessarily by the object they were in. I'll explain the rewrite below:

//  This first line simply calls each section by its class tag and begins the means of operation
$(".section").each(function(i) { // using var i in the function i can keep up with 0 based index of each section i am going thru
    if (!data.sections[i]) { // this simply checks to see if this section exist in array yet, if not, we create it with base params
        data.sections[i] = [{
            id: i,
            duration: 0,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }]
    };
    // add your type oof id to each section if you still want it
    var $this = $(this).attr({ id: "section_"+i });
    // this .each is like a "catchall" to ensure you go thru wach p child of your section and span each char
    $this.children("p").each(function(ii) {
        // save the initial text to a variable for spaning
        var tt = $(this).text();
        // begin your spanning technique, not bad btw
        $(this).html(tt.replace(/\w/g, function(txt, id2) {
            return "<span id="+id2+">"+txt+"</span>";
        }));
        // update the section information in your data array
        data.sections[i].firstSpanIndex = $(this).children("span").first();
        data.sections[i].lastSpanIndex = $(this).children("span").last();
        // made a fatal flaw using .extend as each section of spans get the same id presence, 
        // changed this to .merge which will extend the array regardless of index values
        $.merge(true, spans, $(this).children("span"));
    });
});

Be sure to check out the Fiddle for more information and a working view

Sign up to request clarification or add additional context in comments.

10 Comments

maybe it's a good direction, but the attempts i just tried with it always log's -1 by me.
I tried it like this (even if it would work it would still be incorrect but it would atleast be a step closer): // get first and last span of each section for(var i = 0; i < data.sections.length; i++) { var firstSpanIndex = $("#section_"+i).children("span").first().index(); console.log(firstSpanIndex); var lastSpanIndex = $("#section_"+i).children("span").last().index(); console.log(lastSpanIndex); }
I'm also not sure if i get the children with: for(var i = 0; i < data.sections.length; i++) { console.log($("#section_"+i).children("span")); } I found this console logs very long and confusing.
lol, just got into office will get more specific on this shortly
cool thanks, i will try it out tomorrow when i have time. About the spans array ( // was unsure of your "want/need" ). I wanted to save all spans in a array (no matter what section div) so i could loop over them. So i think that goes wrong now but i think i can manage that.
|
0
+50

For each section, write the first and last indexes in a data attribute.

for the firstIndex and LastIndex, you'll need the offset based on which section your in.

For the firstIndex, check if the span character is the first one in your loop - if so, then calculate it's index value.

For the lastIndex, just keep setting the offset value (the last time in the loop, it'll set the right value.)

Then, somewhere else after your done, you can build your sections array by grabbing the data-attribute values 'data-first-index' and 'data-last-index' for each span.

for(var i = 0; i < data.sections.length; i++) {

  // get the offset for this section - if it's the first one, set it's value to -1
  // if it's not the first one, set it as the data-last-index value
  var offset = i == 0 ? -1 : $('#section_'+i).attr('data-last-index');

  // for each character in your section
  for(var j = 0; j < <number of characters in the section>; j++) {

    var $el = $('#section_'+i);  // cache the dom el

    // set first index - it's simply just the previous lastindex + curr pos + 1
    if (index == 0) {
      $el.attr('data-first-index', offset + j + 1);
    }

    // set last index (everytime, last one in the loop is the last index)
    $el.attr('data-last-index', offset + j);

  });
}

// now you can build your sections array and populate the firstIndex and lastIndex values
// by going $('section_X').attr('data-first-index') => firstIndex value
// and  $('section_X').attr('data-last-index') => lastIndex value

Comments

0

You might want to check out this and this. Use Google Chrome when you click on the links or they won't display properly. They might be able to help you out on what you are trying to achieve.

Comments

0

If I caught you rigth, you might need this:

<head>
<script>

$(document).ready(function(){

var data = {
    sections: [
        {
            id: 0,
            duration: 0,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }, {
            id: 1,
            duration: 7,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }, {
            id: 2,
            duration: 7,
            firstSpanIndex: -1,
            lastSpanIndex: -1
        }]
}   

var spans = new Array();


// span every character
var counter = 0;
for(var i = 0; i < data.sections.length; i++)
{
    //spanEachChar("#section_"+i);
    $("#section_"+i).children().andSelf().contents().each(function(index)
    {
        if (this.nodeType == 3)
        {
            var $this = $(this);
            $this.replaceWith($this.text().replace(/\w/g, function(text,index2)
            {
                if (data.sections[i].firstSpanIndex == -1)
                {
                    data.sections[i].firstSpanIndex=counter;
                }
                data.sections[i].lastSpanIndex=counter;
                counter++;
                return "<span id="+index2+">" + text + "</span>";
            }));
        }
    });
}

// store each span in an array
$("#content span").each(function() {
    spans.push($(this));
});

//console.log("spans.length "+spans.length);

// get them like this
//var span = spans[22];
//console.log(span);

console.log(data);

});
</script>
</head>

<body>

<div id="content">
    <div id="section_1" style="display: none;">
        <p>Goede typografie stimuleert het lezen en heeft als gevolg dat men zo weinig mogelijk moeite hoeft te doen om  een tekst te kunnen lezen. Het moet zo min mogelijk weerstand oproepen om een tekst te kunnen begrijpen.</p>
    </div>

    <div id="section_2" style="display: none;">
        <p>Het vermogen om zeer snel te kunnen lezen en zodoende onze tijd effectief te kunnen gebruiken, hangt vooral af van de wijze waarop de boodschap typografisch is vormgegeven.</p>
    </div>
</div>

</body>

Please note that data.sections[0].firstSpanIndex and data.sections[0].lastSpanIndex remain -1 because there's no div with section_0 so the first available span will be the G of data.sections1

Here you have a fiddle http://jsfiddle.net/u5MMJ/

Here's another one with a div section_0 to show you the difference http://jsfiddle.net/QqjHK/

(check the console in both cases of course)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.