Extend Tumult Hype with JavaScript: hypeDocument.extensions

↑ extension index


hypeDocument.getCurrentSceneHeight

Gets the current scene height.


/**
* hypeDocument.getCurrentSceneHeight 1.0
* @return {Number} height of the scene element
* @require currentSceneElement
*/  
hypeDocument.getCurrentSceneHeight = function () {
    var cS = hypeDocument.currentSceneElement();
    return cS.style.height;
}

Usage:

var height = hypeDocument.getCurrentSceneHeight();

Requires:
hypeDocument.currentSceneElement

1 Like

↑ extension index


hypeDocument.setElementProperties

Sets multiple properties in one go (with the optional possibility to animate them)


20180412-dj7ka

/**
* setElementProperties v1.1
* @param {Element} target to be animated
* @param {Object} object with properties to be animated
* @param {Number} time in seconds for no animation (optional)
* @param {String} easing function (optional)
*/  
hypeDocument.setElementProperties = function ( target, obj, duration, ease) {
    for (var prop in obj) {
        var val = (typeof(obj[prop]) == 'string') ? this.getElementProperty(target, prop) + parseInt(obj[prop]) : parseInt(obj[prop]);
        this.setElementProperty(target, prop, val , duration, ease);
    }
}

Usage:
Given we have element in scene with the id “circle” we can animate it.

var target = hypeDocument.getElementById('someId');
hypeDocument.setElementProperties( target , {top:500, left:267, rotateZ:180}, 1, 'easeinout');

Given we have element in scene with the id “slider” we can slide it relativ to it’s position

var target = hypeDocument.getElementById('slider');
hypeDocument.setElementProperties( target , { left:"-500"}, 1, 'easeinout');

setElementProperties.hype.zip (55,7 KB)

Updates:
1.0 Initial release with multiple property animation
1.1 Added relativ motion if value is String

2 Likes

↑ extension index


hypeDocument.currentSceneIndex

Returns the current scene index (Number).


/**
* hypeDocument.currentSceneIndex 1.0
* @return {Number} gives you the current scene index
*/
hypeDocument.currentSceneIndex = function(){
    var hc = document.getElementById(hypeDocument.documentId());
    var sa = hc.getElementsByClassName("HYPE_scene");
    for (i = 0; i < sa.length; i++) {
        if (sa[i].style.display === "block") return parseInt(sa[i].getAttribute("hype_scene_index"));
    }
}

Usage:
The scene index can also be obtained through element.getAttribute(“hype_scene_index”) in an scene load function but this implementation is agnostic to it’s location and can be used in any Hype function.

var nr = hypeDocument.currentSceneIndex();
1 Like

↑ extension index


hypeDocument.currentSceneElement

Returns the current scene element (HTMLDivElement).


/**
* hypeDocument.currentSceneElement 1.1
* @return {HTMLDivElement} gives you the current scene element
*/
hypeDocument.currentSceneElement = function(){
    return document.querySelector('#'+this.documentId()+' > .HYPE_scene[style*="block"]');
}

As of Hype 4.0.2 (build 656) this new version is the way to go:

/**
* hypeDocument.currentSceneElement 1.2
* @return {HTMLDivElement} gives you the current scene element
*/
hypeDocument.currentSceneElement = function(){
    return document.getElementById(this.currentSceneId());
}

Usage:
Given one would like to share a button function across multiple scenes one could get the current scene element and search for the affected elements using a querySelector contained in the scene. This way you can reuse classes in every scene instead of having different ID’s that would have to be unique across the whole HTML page. This is just one example as I am sure there are more use cases.

var elm = hypeDocument.currentSceneElement();
var someButton = elm.querySelector('.someButton');

Update:
1.0 initial release using getElementById ( :pencil2: see edit history to recall)
1.1 updated version with only one function call

1 Like

↑ extension index


hypeDocument.loadSound

Load soundfiles from the library and plays them back.


/**
* hypeDocument.loadSound 1.0
* @param {String} soundname without extention (mp3/ogg/wav)
* @param {String} uniqueId to load the same sound multiple times (optional)
* @require getPrivateContainer 
* @return {HTMLAudioElement}
*/
hypeDocument.loadSound = function(soundname, uniqueId){
    var soundId = soundname+'_-_'+( (uniqueId===undefined)?'':uniqueId);
    if (!hypeDocument.hasOwnProperty('_sounds')) {
        hypeDocument._sounds={};
    }
    if (!hypeDocument._sounds.hasOwnProperty(soundId)) {
        var pc = hypeDocument.getPrivateContainer('sounds');
        var sndElm = document.createElement('audio');
        if (!!(sndElm.canPlayType && sndElm.canPlayType('audio/mpeg;').replace(/no/, ''))) {
            sndElm.setAttribute('src','${resourcesFolderName}/'+soundname+'.mp3');
        } else {
            sndElm.setAttribute('src','${resourcesFolderName}/'+soundname+'.ogg');
        }
        pc.appendChild(sndElm);
        hypeDocument._sounds[soundId]=sndElm;
        
    }
    return hypeDocument._sounds[soundId];
}

Usage:
Given you have a file called “soundfile.mp3” in your library this function attaches it to your document for further use. The return value is a regular HTMLAudioElement with all it’s functions. Also this functions supports a built in ogg fallback given you supply the file in the library. Wav is currently unsupported (but easy to hack).

var snd = hypeDocument.loadSound('soundfile');
snd.play();

Requires:
hypeDocument.getPrivateContainer

1 Like

↑ extension index


hypeDocument.stopAllSounds

Stops all playing soundfiles that have been loaded with hypeDocument.loadSound


/**
* hypeDocument.stopAllSounds 1.0
*/
hypeDocument.stopAllSounds = function(){
    if (!hypeDocument.hasOwnProperty('_sounds')) {
        return;
    }
    for(var id in hypeDocument._sounds) {
        var snd = hypeDocument._sounds[id];
        snd.pause();
        snd.currentTime = 0;
    }
}

Usage:
Given you have have sounds running that go attached through hypeDocument.loadSound this function will stop them and rewind them to their beginning.

hypeDocument.stopAllSounds();

1 Like

↑ extension index


##hypeDocument.getPrivateContainer
This function creates a kind of “shadow DOM” to hold the audio elements. It’s required by loadSound but also works on it’s own to assist in any other extension.


/**
* hypeDocument.getPrivateContainer 1.0
* @param {String} name for container
* @return {HTMLDivElement}
*/
hypeDocument.getPrivateContainer = function(name){
    var hypeId = hypeDocument.documentId();             
    var hypeElm = document.querySelector('#'+hypeId);
    var pcId = hypeId+'_'+name;
    var pcElm = hypeElm.querySelector('#'+pcId);
    if (pcElm === null){
        pcElm = document.createElement('div');
        pcElm.setAttribute('id', pcId);
        pcElm.style.visibility='none';
        hypeElm.appendChild(pcElm);
    }
    return pcElm;
}

Usage:
Given you need a “shadow DOM” of sorts. This will create a HTMLDivElement inside your HypeDocument and hide it. The return value is a regular HTMLDivElement and can be manipulated as regular. Used for loadSound but should come in handy for other extensions as well. The name parameter is a must to keep each generated container ID unique.

var shadowDom = getPrivateContainer('uniqueName');

1 Like

↑ extension index


hypeDocument.unloadSound

resets the audio element and removes it from the DOM given a HTMLAudioElement to kill.
You will only need this if you are concerned with garbage collection.


/**
* hypeDocument.unloadSound 1.0
* @param soundname
*/
hypeDocument.unloadSound = function(audioRef){
    if (!hypeDocument.hasOwnProperty('_sounds')) return false;
    for(var id in hypeDocument._sounds) {
        if (audioRef === hypeDocument._sounds[id]) {
            var elm = hypeDocument._sounds[id];
            elm.src=''; elm.load();
            elm.parentNode.removeChild(elm);
            delete hypeDocument._sounds[id];
        }
    }
}

Usage:
Given you have a “soundfile.mp3” in your library and loaded it using HypeDocument.loadSound this function will remove the instances by reference. You need to store the reference todo so.

var snd = hypeDocument.loadSound('soundfile');
//makes no sense but let's unload it directly again :-)
hypeDocument.unloadSound(snd);

2 Likes

↑ extension index


hypeDocument.unloadAllSoundsByName

resets all the audio element and removes them from the DOM given the library name (without mp3/ogg)
You will only need this if you are concerned with garbage collection.


/**
* hypeDocument.unloadAllSoundsByName 1.0
* @param soundname
*/
hypeDocument.unloadAllSoundsByName = function(soundname){
    if (!hypeDocument.hasOwnProperty('_sounds')) return false;
    var success = false;
    for(var id in hypeDocument._sounds) {
        if(id.indexOf(soundname+'_-_') == 0){
            var elm = hypeDocument._sounds[id];
            elm.src=''; elm.load();
            elm.parentNode.removeChild(elm);
            delete hypeDocument._sounds[id];
            success = true;
        }
   }
   return success; 
}


Usage:
Given you have a “soundfile.mp3” in your library and are using it multiple times (see loadSound for details) this function will remove all instances by name.

hypeDocument.unloadAllSoundsByName('soundfile');

1 Like

↑ extension index

hypeDocument.cloneElement

This Extension allows you to clone elements and append them to the scene or within a Group.
You will specify the Element to clone, where to append the clone, it’s ID, Class Name, Top, Left and z-Index.
The clones HYPE_element_container class name, Child Nodes ID and HYPE_element classes are removed from the clones to avoid clashes with the Hype runtime.

/**
    * cloneElement, can be single Element or Group
    * @param {element} Hype Element to  clone
     * @param {element} Hype Element to append the clone
    * @param {String} The clone's id
    * @param {String} The clone's class name
    * @param {numnber} The clone's Top placement
    * @param {numnber} The clone's Left placement
    * @param {numnber} The clone's z-index
    * @return the specified element is cloned and appended to the specified element. The clones HYPE_element_container class name, Child Nodes ID and HYPE_element classes are removed from the clones to avoid clashes with the Hype runtime.
    */	  
    	hypeDocument.cloneElement = function(elementToClone,clonTo,elementID,elementClassName,elementTop,elementLeft,elementZIndex){
    	var elementClone =   elementToClone.cloneNode(true, true);
      
    	elementClone.id = elementID ;
    	elementClone.className = elementClassName;

    	elementClone.style.top = elementTop.toString() +'px';
    	elementClone.style.left = elementLeft.toString() +'px';
    	elementClone.style.zIndex = elementZIndex.toString();  
    		  
    	clonTo.appendChild(elementClone);
    	
    	
    	var clonedChildren = elementClone.childNodes

    for (i = 0; i < clonedChildren.length; i++) { 
     
    clonedChildren[i].classList.remove("HYPE_element_container");
     
      	var thisChild = clonedChildren[i].childNodes[0];
      	thisChild.classList.remove("HYPE_element");
     	thisChild.id  = "" ;

 } 
	
	return elementClone;
    	
    	
    	}

Usage:
You may have a form that you want to dynamically add elements to it’s list.

Constructor:
hypeDocument.cloneElement(original_to_clone,append_the_clone_To, id,className,top,left,z-index)

In Use:

if (!window.start_Top) { window.start_Top = 0 }; //-- This will be the space between the new clones and we will also use this number in the new ids.
    		
    		if ( window.start_Top < 200 ){ //-- Limit to 2 new clones
    		
    		window.start_Top +=100
    			
    		var original_to_clone  = hypeDocument.getElementById('infoBoxGroup'); 
     
     		/* We use the Scene element here to append the clones but we could use any Div/Group in the scene i.e  hypeDocument.getElementById('clonToFoo'); */
     		var append_the_clone_To = hypeDocument.currentSceneElement(); //-  @REQUIERS  currentSceneElement  Extension.

     //-- clone
    hypeDocument.cloneElement(original_to_clone,append_the_clone_To,'infoBoxGroupClone'+ window.start_Top,'infoBoxGroupClone',window.start_Top,0,2000)

     
    }

In this example we want a couple of clones so we also use the top’s number as an index to limit the cloning to two and also we use it in the new ids to keep them original.

Note: This example also uses currentSceneElement Extension.


Version update 1.1

Added a return of the clone element. You will now be able to add the returned clone element to a var or send it instructions.

clone Extension_Example_v1_MH.hype.zip (27.9 KB)

3 Likes

Awesome Max

I added relativ motion to hypeDocument.setElementProperties (if value is given as string)

1 Like

↑ extension index


hypeDocument.goToTimeIndexInTimelineNamed

Jump to timeIndex as seen in the Hype frontend.


/**
* hypeDocument.goToTimeIndexInTimelineNamed 1.0
* @param {String, Object, Number} timeIndex as seen in Hype GUI
* @param {String} time line to adress
* @param {Boolean} convert overbound values
*/
hypeDocument.goToTimeIndexInTimelineNamed = function (timeIndex, timelineName, convert) {
    this.goToTimeInTimelineNamed( this.timeIndexToSeconds(timeIndex, convert), timelineName);
}

/**
* hypeDocument.timeIndexToSeconds 1.2
* @param {String, Object, Number} timeIndex in various formats
* @param {Boolean} convert overbound values 
*/
hypeDocument.timeIndexToSeconds = function (tidx, convert) {
	var min=0, sec=0, frm=0, FPS=30;
	switch (typeof(tidx)) {
		case 'object':
		 min = tidx.minutes ? tidx.minutes : 0;
		 sec = tidx.seconds ? tidx.seconds : 0;
		 frm = tidx.frames ? tidx.frames : 0;
		 FPS = tidx.FPS ? tidx.FPS : FPS;
		 break;
		case 'number':
		 sec = Math.floor(tidx);
		 frm = Math.floor((tidx-sec)*100);
		 break;	
		case 'string':
		 var temp = tidx.split(':');
		 min = temp.length > 1 ? temp[0] : 0;
		 temp = (temp.length > 1) ? temp[1] : temp[0];
		 temp = temp.split(temp.indexOf('.') > -1 ? '.' : ',');
		 sec = temp[0] ? temp[0] : 0;
		 frm = temp.length > 1 ? temp[1] : 0;
		 break;
	}
	sec = (convert) ? sec : sec %60;
	min = (convert) ? min : min %60;
	frm = (convert) ? frm : frm %FPS;
	return min*60+sec+frm/FPS;
}

Usage of hypeDocument.timeIndexToSeconds:
Let’s assume we want to jump to 3 seconds and 14 frames :wink:

// EU notation
hypeDocument.goToTimeIndexInTimelineNamed ('03,14', 'Main Timeline');
// US notation
hypeDocument.goToTimeIndexInTimelineNamed ('03.14', 'Main Timeline');

Let’s assume we want to jump to frame number 75 on test timeline (Object-Interface)

hypeDocument.goToTimeIndexInTimelineNamed ({frame:75}, 'test', true);

See possible formats for the timeIndex-String in the timeIndexToSeconds usage.

 

 

Usage of hypeDocument.timeIndexToSeconds:

// New FPS option in Object-Interface since 1.2 
// Converting 120 frames at 60 FPS (works with other examples as well)
console.log(hypeDocument.timeIndexToSeconds( {frames:120, FPS:60 } , true ));

// New object interface since 1.1
console.log(hypeDocument.timeIndexToSeconds( {minutes:1, seconds:10} ));
console.log(hypeDocument.timeIndexToSeconds( {minutes:1} ));

// with conversion 45 frame equals 1.5 seconds
console.log(hypeDocument.timeIndexToSeconds( {frames:45 } , true ));

// Number interface since 1.1 (limited to sec.frames)
console.log(hypeDocument.timeIndexToSeconds( 4.15 ));

// New String interface since 1.1 (valid tests with US dot notation)
console.log(hypeDocument.timeIndexToSeconds('01:40.15'));
console.log(hypeDocument.timeIndexToSeconds('30.00'));
console.log(hypeDocument.timeIndexToSeconds('02:43.29'));

// String interface since 1.0 (valid tests)
console.log(hypeDocument.timeIndexToSeconds('01:40,15'));
console.log(hypeDocument.timeIndexToSeconds('30,00'));
console.log(hypeDocument.timeIndexToSeconds('02:43,29'));

// wrong range tests (fixed with modulor %60, %30
console.log(hypeDocument.timeIndexToSeconds('00:61,40'));

// partial format (no minutes)
console.log(hypeDocument.timeIndexToSeconds('25,02'));

// partial format (no frame)
console.log(hypeDocument.timeIndexToSeconds('1:15'));

// partial format (only one int)
console.log(hypeDocument.timeIndexToSeconds('15'));

// conversion (45 frames)
console.log(hypeDocument.timeIndexToSeconds(',45', true));

// conversion (120 minutes)
console.log(hypeDocument.timeIndexToSeconds('120:', true));

Credits:
This extension has been initialized by @MarkHunte :sparkles:
The version bump came about through input from @DBear

Update:
1.0 inital relase from MarkHunte and MaxZieb
1.1 fixed .frames (US) and ,frames (EU) + Number/Object interface
1.2 timeIndexToSeconds now supports higher FPS (for example 60)

4 Likes

Updated hypeDocument.startCustomBehaviourTicker to version 1.1:

  • it now support patterns and omitFirst options
1 Like

↑ extension index


hypeDocument.sceneInfo

This Extension returns the scene element, scene number and scene count, scene name list
.

		
	
	
	
/* hypeDocument.sceneInfo 1.0
* @return {object} gives you the current scene, Name, number and the total count of scenes.  {sceneName: currentSceneName, sceneNumber:Number,sceneElement:Element,sceneCount: Number}

* @Returned object break down
  sceneName = The current scene's name Type: String 
 sceneNumber = The current scene's display order number Type: Number 
 sceneElement = The current Scene's Div Element  Type: Hype Element 
 sceneCount = Total count of all scenes  Type: Number 
*/

 hypeDocument.sceneInfo = function(){
 
var sceneElement;
 //-- get current scene
 var hypeContainer = document.getElementById(hypeDocument.documentId());
    var scenArray = hypeContainer.getElementsByClassName("HYPE_scene");
    for (i = 0; i < scenArray.length; i++) {
        if (scenArray[i].style.display === "block")  sceneElement = scenArray[i];
    }

 


 
  	var sceneNumber = sceneElement.getAttribute('hype_scene_index');// get the index number of the current scene name. Add 1 to make the index start from 1 instead of 0.
	var currentSceneName = hypeDocument.currentSceneName(); // get the curent scene name 
	var sceneNameArray = hypeDocument.sceneNames();  // get an array of all scene names 
	  

	return {sceneName: currentSceneName, sceneNumber: Number(sceneNumber)+1 ,sceneElement: sceneElement ,sceneCount: Number(sceneNameArray.length)}
  
  }

Returned object break down
sceneName = The current scene's name, Type: String
sceneNumber = The current scene's display order number, Type: Number
sceneElement = The current Scene's Div Element, Type: Hype Element
sceneCount = Total count of all scenes, Type: Number

Usage:

var sceneInfo = hypeDocument.sceneInfo()

You may want to set a navigation label to display scene name and numbers,

fooElement.innerHTML = sceneInfo.sceneName + " - " + sceneInfo.sceneNumber + " of " + sceneInfo.sceneCount ;

--> fooSceneName - (1 of 5)


Get the current scene element so you can target a child element that shares a class name with similar elements on other scenes.

var someButton = sceneInfo.sceneElement.querySelector('.someButton’);


Example:

ScenInfo Extension.hype.zip (31.6 KB)

Extension code ( text file )

hypeDocument.sceneInfo 1.0.txt.zip (1.2 KB)

3 Likes

↑ extension index


hypeDocument.setInnerHtmlByClass

Sets all the all elements of a given class to the content one provides. Usefull to update content across scenes and layouts all at once. Elements that want to subscribe to content updates only need to be assigned the associated class


Reasons for using class based targeting over ID based targeting:

  1. Hype has a unique approach when it comes to responsive layouts. As with scenes themselves it keeps them in own HTML braches. Meaning when you have to repeat using elements per scene or layout … ID’s demand to be unique. Therefor it would be very annoying to have to choose a different ID per scene or layout for the same content.
  2. Addressing the content nodes per Class allows them to be in plentiful locations and they are all updated at once without the need to target any element specifically.
  3. One can also use persistent symbols and unique ID’s but one often needs to tweak the design beyond proportional symbol scaling and that is where this technic really helps.

/**
* hypeDocument.setInnerHtmlByClass 1.0
* @param {String} class name to overwrite (don't include dot)
* @param {String} content or HTML used to overwrite class
*/
hypeDocument.setInnerHtmlByClass = function(cl, content) {
    var hypeDiv = document.getElementById(this.documentId());
    var hypeElm = hypeDiv.getElementsByClassName(cl);
    for(var i=0; i<hypeElm.length; i++){
            hypeElm[i].innerHTML=content;
    }
}

Usage:
Presume you have a textfield with the class userName and want to update it:

hypeDocument.setInnerHtmlByClass ('userName', 'Max');

setInnerHtmlByClass.hype.zip (127,2 KB)

4 Likes

↑ extension index


hypeDocument.getSceneElementByName

Returns a scene element by name (HTMLDivElement).


/**
* hypeDocument.getSceneElementByName 1.0
* @return {HTMLDivElement} gives you the scene element by name
*/
hypeDocument.getSceneElementByName = function(name){
    var idx = this.sceneNames().indexOf(name);
    return document.querySelector('#'+this.documentId()+' > .HYPE_scene[hype_scene_index="'+idx+'"]');
}

Usage:
Lets assume you want to extract the text contained in an textfield in another scene called intro.

var elm = hypeDocument.getSceneElementByName('intro');
var txt = elm.querySelector('#mytextbox').value;

Update:
1.0 initial release

2 Likes

↑ extension index


hypeDocument.continueTimelineNamedFromTo

This Extension allows you to play a Timeline from a given time, To a given time on a named timeline

The timeline will start from the From time and stop at the To time.



      /* hypeDocument.continueTimelineNamedFromTo 1.0
     * @description This Extension allows you to play a Timeline **from** a given time,  **To** a given  time  on a **named**  timeline
     
     The  timeline will start from the **From time** and  stop at the  **To time**.
     
      *@param  (Number/String) timelineNamed = The Timeline name to act on
      *@param  (Number/String) timeFromSeconds = The time to start from
      *@param  (Object) playOptions =  play to time in time line , Dirctional play option -  {timeToSeconds: time (Number/String), kDirection: (hypeDocument.kDirection)}
     
     */



    hypeDocument.continueTimelineNamedFromTo = function(timelineNamed,timeFromSeconds,playOptions){
        
        
        //-- set the start time
        timeFromSeconds =	 timeType(timeFromSeconds)
        
        
        //-- set the direction
        var kDirection = hypeDocument.kDirectionForward;
        var restartTimeline = false;
        if (playOptions){
        
        if (playOptions.hasOwnProperty('kDirection'))  {
            
            
            kDirection = playOptions['kDirection'];
            
            
        }
        }
        
        //-- pause, Go to start time , continue timeline
        //hypeDocument.pauseTimelineNamed(timelineNamed)
        hypeDocument.goToTimeInTimelineNamed(timeFromSeconds, timelineNamed)
        hypeDocument.continueTimelineNamed(timelineNamed, kDirection,restartTimeline)
        
        
        //-- set the end time
         if (playOptions){
        if (playOptions.hasOwnProperty('timeToSeconds'))  {
            
            var timeToSeconds =	 timeType(playOptions['timeToSeconds']);
            
            //--- compare left, right = start time end time.
            
            //-- start the end time timer.
            var timeCodeStop = setInterval(function(){
                                           var compareLeft , compareRight;
                                           
                                           
                                           
                                           //-- set up the end time timer. Check which direction we are going in. If reverse swap the start and end time around. This is so we can use a single > symbol below.
                                           
                                           kDirection === hypeDocument.kDirectionReverse ? (
                                                                                            
                                                                                            
                                                                                            
                                                                                            //-- reverse
                                                                                            compareLeft = timeToSeconds ,
                                                                                            compareRight = hypeDocument.currentTimeInTimelineNamed(timelineNamed).toFixed(3)
                                                                                            
                                                                                            
                                                                                            ) : (
                                                                                                 
                                                                                                 compareLeft = hypeDocument.currentTimeInTimelineNamed(timelineNamed).toFixed(3) ,
                                                                                                 compareRight = timeToSeconds 
                                                                                                 
                                                                                                 );
                                           
                                           
                                           if (compareLeft >  compareRight ){
                                           console.log("stop"); //this one
                                           
                                           
                                           hypeDocument.pauseTimelineNamed(timelineNamed)
                                           
                                           clearInterval(timeCodeStop);
                                           
                                           
                                           
                                           };
                                           
                                           
                                           
                                           
                                           }, 20);
            
            
        };
        
    }//--End if playOptions
    };




     		 
    //-- Time split Functions  -->	
    function timeType(timeSeconds){
        
        switch (typeof(timeSeconds)) {
                
            case 'number':
                timeSeconds  = numberSplitTime(timeSeconds)
                break;	
            case 'string':
                timeSeconds  = stringTimeSplit(timeSeconds)
                break;
        }
        
        return timeSeconds
    }



    function numberSplitTime(timeM){
        
        var secs =  timeM.toFixed(0)  ;
        var mils =  (timeM  -  secs).toFixed(2).replace(".","")  
        
        
        return   mils =  Number(secs) + ( Number(mils) * 0.033 )
        
        
    }	





    function stringTimeSplit(tidx){
        
        
        var tempNumbers = [];
        var finalNumbers = []
        
        
        var tidxArrary = tidx.split('')
        tidxArrary.push(':');
        
        for (i = 0; i < tidxArrary.length; i++) { 
            
            if (!tidxArrary[i].match(/\D/)){
                tempNumbers.push(tidxArrary[i]);
                
            }else{
                
                var tempNum = tempNumbers.join('');
                finalNumbers.push(tempNum);
                tempNumbers =[];
            }
            
            
        }
        
        var splitTime = Number(finalNumbers[0]) * 60 + Number(finalNumbers[1]) + ( finalNumbers[2] * 0.033 )
        
        return [splitTime];		
        
    }



    //<---/

You can add an optional Direction to play timeline:

hypeDocument.kDirectionForward
hypeDocument.kDirectionReverse


Time Syntax

The Time syntax is Strict but can be done in a number format seconds.frames or in a String format “min:seconds.frame

The number format is the same as the standard hype API.

Examples of time using numbers.
seconds.frames

1.34
34.10
70.14

Frame index does not exceed 29.


Examples of time using String syntax.

min:seconds.frame

‘00:34.15’
‘00:34,15’

‘01:10,14’
‘01:10.14’

‘1:10,14’
‘1:10.14’

The seconds must not be greater than 59 and the frame must not be more than 29.


Call Syntax.
hypeDocument.continueTimelineNamedFromTo(timelineName (String) , time# (Number/Sting), {timeToSeconds: time# (Number/Sting), kDirection: (hypeDocument.kDirectionForward/ Reverse API) } )


Usage

Using numbers time.

We want the time line to play from the 34 seconds and 10 frames point and stop at the 70 seconds and 14 frames point. And forward

hypeDocument.continueTimelineNamedFromTo(“fooTimeline”, 34.10, {timeToSeconds:70.14 , kDirection: hypeDocument.kDirectionForward})


Using string time.

We want the time line to play from the 70 seconds and 14 frames point and stop at the 34 seconds and 10 frames point. And in Reverse

hypeDocument.continueTimelineNamedFromTo("test", '01:10:14’ , {timeToSeconds: '00:34.10’, kDirection: hypeDocument.kDirectionReverse})


Play Options

kDirection: is Optional. The default is forward.

hypeDocument.continueTimelineNamedFromTo(“fooTimeline”, 34.10, {timeToSeconds:70.14 })

But use hypeDocument.kDirectionReverse when you are starting down the time stream and playing back up time stream to a near time. (reverse)

hypeDocument.continueTimelineNamedFromTo("foo2",'00:08:10' , {timeToSeconds: '00:2.25', kDirection: hypeDocument.kDirectionReverse})


timeToSeconds : is Optional.

You can exclude this option and just use the start from time.
The timeline will then start from the given time and continue as normal.

hypeDocument.continueTimelineNamedFromTo(“fooTimeline”, 34.10)

hypeDocument.continueTimelineNamedFromTo(“fooTimeline”, 34.10, {kDirection: hypeDocument.kDirectionReverse})

You can use either one or the other options, Both or none.


Example project.

ContinueTimelineNamedFromTo.extension v1 Example.hypetemplate.zip (43.5 KB)

v1.00


Also see example in this post


Tip

You can use the current time of a timeline using this syntax.

var currentTime = hypeDocument.currentTimeInTimelineNamed(timeline).toFixed(3)


If you do need to use the current time API make sure you chain .toFixed(3) to the end.

var currentTime = hypeDocument.currentTimeInTimelineNamed(timeline).toFixed(3);

hypeDocument.continueTimelineNamedFromTo(timeline,'00:1.00' ,  {timeToSeconds: currentTime , kDirection: hypeDocument.kDirectionReverse})
6 Likes

↑ extension index

hypeDocument.TypeTextExtension

hypeDocument.TypeTextExtension = function(obj ){ 
/*

		Markhunte 2023  version 1.3.3
	@1.3.3  -- 
	-Removed Bullet characters in the comments as they could stop some export scripts working ??.

		Markhunte 2018  version 1.3.2 
			@1.3.2  -- 
			-Fixed bug that stopped no cursor runs from completing. - misplaced } and also needed extra check on if blinker is running 
			so we do not restart it by mistake at end of run.
			-change to touchend. iOS seemed to show the keyboard and then hide. (need to investigate further)
			-set the input div (iOS) to -200px top as it was showing through the Mobile Safai semi transparent menu bar
			
			
		@1.3.1  -- 
			-Put the blinker setInteval in a function so we can stop and start it. 
			This allows us to set the speed for auto type to give a better affect.
		
			-Added vertical-align:top to the blinker span. This sets the top of the span/cursor to the top of the parant div. 
			This helps stop jumping of the text as the span will try to adust the size of the text line
			
			-Added cursorVerticalAlign:   option to the cursor options. This allow for use manual control of vertical-align of the cursor
  			
  			-Added  cursorLineHeight: option to the cursor options. this allow for use manual control of line-height of the cursor
  			
		@version 1.3.0  -- 
			removed the need for jquery, Change Cursor options mapping
		
		
		
		
 @Construtor Example
  
  hypeDocument.TypeTextExtension({
        	textElement:textElement,
        	typeType:"keydown",
            hasCursor: {
        cursor:"*" ,
        cursorFontSize:120,
        cursorLineHeight:'120%',
    	cursorColour:"pink" },
        	 typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
            	})
	

@Construtor object break down
		**Required Properties** 
		 
	*@param  textElement : (Element) = the Hype element that will show the Typed text. This normally will be a Text Box or a Rectangle.
   	*@param   typeString : (String) = is the text that will be typed out, You can add line breaks/newlines by using the standard html tag  `<br>`
   	
**Override Automatically Typing Options**

	*@param  (String) typeType =  You can turn off Automatically Typing and set the Typing behaviour to type one character per keydown
	*@param  (Number) autoTypingSpeed  =  You can change the Automatic Typing speed to you desired speed.
												The speed is measures in thousands of a second. The number 1000= 1s,  400 = 0.4s.
												Enter the Number in in Integer form. i.e  100, 122, 400

**Optional Cursor.**
												
*@param  (true:Bool) hasCursor  = . You can add a blinking cursor. The cursor can be use with Auto typing and Keydown typing.

**Override Cursor defualt Options**

------
For Cursor options replace  hasCursor:true,

with

 hasCursor: {
        cursor:"*" ,
        cursorFontSize:120,
        cursorLineHeight:'120%',
    	cursorColour:"pink" },
-----
*@param  (String) cursor =  Change the symbol for the cursor. A Character, String, Emoji can be used.
*@param  (Int:Number) cursorFontSize = 	This is handy if the Chosen font of the Text Element means the cursor symbol is appearing small.
											Enter a number here of the equivalent pixel size you want.
											
*@param  (String) cursorLineHeight = You can adjust this with the _cursorLineHeight_ option. 
											Enter either the pixels '`100px'` or percentage  '`120%'` you want the height to drop in cursor to.
											
*@param  (String) cursorColour = 	Change the cursor colour,Enter either a a Named colour "red" or a hex colour "#EDD039". Remember to try and use web safe colours.

**extra Cursor Option**

*@param  (String) cursorVerticalAlign =  This overrides the **top** default of **vertical-align**.

There may be times when you want or need to set the vertical-align to either `"middle"` or `"bottom"`

The cursor is set in it's own `<span>`  when the cursor blinks it is doing so by using display properties.
this means it may, depending on font and size, adjust the Text Box size/padding. This appears as jumping Text.
The default of top accounts for this in most cases.
									
*/


if(typeof obj.textElement == "undefined"){throw new Error("No Element has been added constructor hypeDocument.TypeTextExtension to recieve the string");return } 
if(typeof obj.typeString == "undefined"){ throw new Error("No typeString has been added to the constructor hypeDocument.TypeTextExtension");return }
if(typeof obj.autoTypingSpeed == "undefined"){ obj.autoTypingSpeed = 200}
if(typeof obj.autoTypingSpeed != "number"){ throw new Error("The  autoTypingSpeed added to the constructor hypeDocument.TypeTextExtension, must be a number. Not " + (typeof obj.autoTypingSpeed) );return }   

 
 window.blinkerOn = false; 
if (obj.hasOwnProperty('hasCursor')){
 
 
  if ( obj.hasCursor.hasOwnProperty('cursorFontSize') == false ){
   window.cursorFontSize =  parseInt(obj.textElement.style.fontSize,10)  } else { window.cursorFontSize =  obj.hasCursor.cursorFontSize}
 if(typeof  window.cursorFontSize != "number"){ throw new Error("The cursorFontSize added to the constructor hypeDocument.TypeTextExtension, must be a number. Not " + (typeof  window.cursorFontSize) );return }   
 //
 
 if ( obj.hasCursor.hasOwnProperty('cursorColour') == false ){
   window.cursorColour = "#2F9DEC"   } else { window.cursorColour =  obj.hasCursor.cursorColour}
 //
 if (obj.hasCursor.hasOwnProperty('cursor') == false ){
   window.cursor = "|"   } else { window.cursor =  obj.hasCursor.cursor}
 //
if (obj.hasCursor.hasOwnProperty('cursorVerticalAlign') == false ){
 window.cursorVerticalAlign = "top"   } else { window.cursorVerticalAlign =  obj.hasCursor.cursorVerticalAlign} 
  //
  
 if (obj.hasCursor.hasOwnProperty('cursorLineHeight') == false ){
 
 window.cursorLineHeight = obj.textElement.style.lineHeight   } else { window.cursorLineHeight =  obj.hasCursor.cursorLineHeight}
 if(typeof  window.cursorLineHeight != "string"){ throw new Error("The cursorLineHeight added to the constructor hypeDocument.TypeTextExtension, must be a Sting. i.e \"90px\" or \"90%\". Not " + (typeof  window.cursorFontSize) );return }   
 //

  }
  
   
  
  window.blinker = ""
  window.blinkspeed = 600	
  window.textElement = obj.textElement;
  window.charS = obj.typeString
  var newDiv = document.createElement("DIV");

 
	window.autoTypingSpeed = obj.autoTypingSpeed
	   
 	//**--ADD DIV AND INPUT Field FOR iOS. This allows the typed text to show without the IOS cursor showing.
 	//-- The text that hits the input which is off scene will be mirroed in the hype scene text.
	var newDiv = document.createElement("DIV");
	newDiv.setAttribute('style', 'top: -200px; position: absolute');
	
	 newInput = document.createElement("INPUT");
    newInput.id = "Input"  
     newInput.setAttribute('style','font-size: 48px')//- This is only for iOS so we do not get zooming whe we focus.

   window.foo_label = document.createElement("Label");
 		window.foo_label.htmlFor = "Input" 
     	window.foo_label.value= "";
    	window.foo_label.className = "foo_Label"
  
 		newDiv.appendChild(newInput)
    	newDiv.appendChild(window.foo_label)
    
  		document.body.appendChild(newDiv)
  		
  //*-End iOS DIV ADD
   
  //START BLINKER
  if (obj.hasOwnProperty('hasCursor')){
  
  
  //	window.blinker  = "<span id=\"blinker\" style=\"vertical-align:middle; font-size:" +  window.cursorFontSize + "px ;color:" + window.cursorColour + "!important\">" + window.cursor + "</span>";
	
	window.blinker  = "<span id=\"blinker\" style=\"line-height:" + window.cursorLineHeight + ";vertical-align:" + window.cursorVerticalAlign +"; font-size:" +  window.cursorFontSize + "px ;color:" + window.cursorColour + "!important\">" + window.cursor + "</span>";
	window.textElement.innerHTML = window.blinker
	
	 console.log('HERE')
	//-- Start the cursor blinking
	 startBlink()
	  window.blinkerOn = true
 //
	} //---<<<<
if(typeof obj.typeType == "undefined"){ 
 
  obj.typeType ="auto"
  
  }
   var typType = obj.typeType.toLowerCase()
  
  switch(typType) {
    case "auto":
        isAutoType()
      
        break;
    case "keydown":
       isKeydownType()
        break;
    default:
       isAutoType() 
}
  
////-----
  
  //
  
  	function isKeydownType(){
  	 
  	 //-- For iOS	   
  	window.textElement.addEventListener('touchend', function(event) {
 
  
   console.log('focus')
   window.foo_label.focus()
  
  });
  
  	
	 document.addEventListener('keydown', function(event) {
     
	
	var charArray = window.charS.split('');
	 
	if (! window.indexer){window.indexer =0};  
	  
	//-- start typing

 
 	 if (window.indexer == charArray.length){
	 
	  return;
	 }
	 
     var charItem = charArray[window.indexer];
     
    
    
     if  (charItem == "<" ) {
if  (charArray[window.indexer +1] == "b" && charArray[window.indexer +2] == "r" && charArray[window.indexer +3] == ">") {
     charItem = "\<br\>";
     window.indexer = window.indexer + 3
}
     }
  
    if (window.blinker != ""){
  var blinkR = document.querySelector("#blinker") ;
 blinkR.remove() 
 }
   
	 window.textElement.innerHTML =  window.textElement.innerHTML + charItem  + window.blinker
  		window.indexer++;
    }, false);
	
 
	  

  	}
  	
  	function isAutoType(){
  	window.blinkspeed = 300
  	clearInterval(window.thisBlinkerFire);
	 if (window.blinkerOn){
	 startBlink()	
	 }
	 
	var charArray = window.charS.split('');
	
	
	var counter;
	var i=0;


//-- add characters and remove last cursor/blinker, ad new blinker after last character
 window.thisFire =   setInterval(function(){
	 
	 if (i == charArray.length){
	 clearInterval( window.thisFire);
	 clearInterval(window.thisBlinkerFire);
	 window.blinkspeed = 600
	 if (window.blinkerOn){
	 startBlink()	
	 }	
	  return;
	 }
     var charItem = charArray[i];
     
     if   (charItem == "<" )     {

if  (charArray[i +1] == "b" && charArray[i +2] == "r" && charArray[i +3] == ">") {
 
     charItem = "\<br\>";
		i = i + 3
		
		}
     }
     
     
     if (window.blinker != ""){
  var blinkR = document.querySelector("#blinker") ;
  
    blinkR.remove()
 
 }
   
    
     
	 textElement.innerHTML =  textElement.innerHTML + charItem  + blinker;

  		i++;

	 }, window.autoTypingSpeed);
  	}	
  	
  	
  	function startBlink(){
  	
  	window.thisBlinkerFire =   setInterval(function(){
	  
	
	  
    var blinker = document.getElementById("blinker");
    
    if (blinker.style.display === "none") {
        blinker.style.display = "inline";
    } else {
       blinker.style.display = "none";
    }
  
	  
	  }, window.blinkspeed);
  
  
  }
  	
  
  	//-- Remove poly fill for IE
  	(function (arr) {
  arr.forEach(function (item) {
    if (item.hasOwnProperty('remove')) {
      return;
    }
    Object.defineProperty(item, 'remove', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function remove() {
        if (this.parentNode !== null)
          this.parentNode.removeChild(this);
         //console.log( 'ieremove');
      }
    });
  });
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
  	
  }//Main END

This Extension allows you to have a text string be typed out like it would on a type writer.

You can choose with Auto Type (The text will automatically type out ) or by keydown. (The text will type 1 character for any keydown event.

Line breaks/newlines can be added to the string using the standard <br> code.

You will be able to set a blinking cursor's, colour and symbol.

Construtor Example

      hypeDocument.TypeTextExtension({
            	textElement:textElement,
            	typeType:"keydown",
                hasCursor: {
            cursor:"*" ,
            cursorFontSize:120,
            cursorLineHeight:'120%',
        	cursorColour:"pink" },
            	 typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
                	})

Required Properties

hypeDocument.TypeTextExtension({
	textElement: aTextElement,
	 typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
	})

required: textElement: : Element

The textElement property is for the Hype element that will show the Typed text. This normally will be a Text Box or a Rectangle.

Simply acquire the element object as normal.

var aTextElement = document.getElementById('textBox');


textElement: aTextElement,


required: typeString : String

The typeString is the text that will be typed out.

You can add line breaks/newlines by using the standard html tag <br>
The String will take on the Font and other properties set for the textElement text box/rect



The Default Typing behaviour

The default behaviour of the typing:

• Automatically typing of the text.

  • Typing speed is one Char every 200th of a second.
    • No Cursor.

Override Automatically Typing Option

optional: typeType : String

You can turn off Automatically Typing and set the Typing behaviour to type one character per keydown
The Keydown single Char typing will also Work on iOS. The default iOS cursor will not show and the Zooming should also not zoom. Limited testing on iOS. No testing done on other Mobile devices

typeType:"keydown",

hypeDocument.TypeTextExtension({
	textElement:textElement,
	typeType:"keydown",
	 typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
    	})

Override Automatically Typing speed Option

optional: autoTypingSpeed : Number

You can change the Automatic Typing speed to you desired speed. The speed is measured in thousands of a second. The number 1000= 1s, 400 = 0.4s.

Enter the Number in in Integer form. i.e 100, 122, 400


autoTypingSpeed: 400,

hypeDocument.TypeTextExtension({
	textElement:textElement,
    autoTypingSpeed: 400,
	 typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
    	})


Optional Cursor.

optional: hasCursor : Bool > true

You can add a blinking cursor. The cursor can be use with Auto typing and Keydown typing.


hasCursor: true,

 hypeDocument.TypeTextExtension({
    	textElement:textElement,
    	typeType:"keydown",
        hasCursor: true,
       typeString:"Here is some text to type out <br> And this is a second line. <br><br><br> This is a third line with 3 returns above"
        	})

The Default Cursor behaviour

  • Blinking

  • Symbol = | ( a pipe)

  • Colour = #2F9DEC

  • vertical-align= Top

  • line-height = The same as the Text Box/Rect.

The cursor by default will blink, It will appear as a line similar to a normal typing cursor, It will have a default slightly blue colour, It's will normally try to align to the top of the Text. ( depending on fonts etc.) It's line height will match the Text's line height.

Override Cursor Options

You can override some default properties of the cursor.

hasCursor: {
    cursor:"*" ,
    cursorFontSize:120,
    cursorLineHeight:'120%',
	cursorColour:"pink" },

optional: cursor : String > Character ,String, Emoji etc

Change the symbol for the cursor. A Character, String, Emoji can be used.


optional: cursorFontSize : Number >Int

This is handy if the Chosen font of the Text Element means the cursor symbol is appearing small.
Enter a number here of the equivalent pixel size you want.


optional: cursorLineHeight : String

Sometimes the Size of the cursor may affect the height of the cursor in relation to the Text.
For example It may ride slightly above the text.

You can adjust this with the cursorLineHeight option. Enter either the pixels '100px' or percentage '120%' you want the height to drop in string form.


optional: cursorColour : String

This allows you to Change the colour of the Cursor Symbol. If you use an Emoji the colour will not change.

Enter either a a Named colour "red" or a hex colour "#EDD039". Remember to try and use web safe colours.


extra Cursor Option

optional: cursorVerticalAlign : String

This overrides the top default of vertical-align.

There may be times when you want or need to set the vertical-align to either "middle" or "bottom"

The cursor is set in it's own <span> when the cursor blinks it is doing so by using display properties. this means it may, depending on font and size, adjust the Text Box size/padding. This appears as jumping Text. The default of top accounts for this in most cases.

Example project.

Version: 1.3.3 (27-01-2023)
-Removed Bullet characters in the comments as they could stop some export scripts working ??.

TypeTextExtension_v133.hypetemplate.zip (20.7 KB)


Reloading scene:
The extension runs on document load.
There may be an occasion where you want to reload the scene with the typing and have the typing start from scratch.

You will need to shut down the current typing text when the scene loads, otherwise you will get multiple instances of typing text competing for space.

Simply add

clearInterval( window.thisFire);
clearInterval(window.thisBlinkerFire);

to the top of you construction function.

i.e

clearInterval( window.thisFire);
clearInterval(window.thisBlinkerFire);
 
var textElement = document.getElementById('textBox');
  
  hypeDocument.TypeTextExtension({
	textElement:textElement,
		typeType:"auto",
	autoTypingSpeed:400,
	 typeString:"Here a sentence <br>will be written ",
	 
hasCursor: {
    cursor:"|" ,
    cursorFontSize:70,
    cursorLineHeight:'130%',
	cursorColour:"white" },
	 
	})

You can use the.

clearInterval( window.thisFire);
clearInterval(window.thisBlinkerFire);

where ever you need to stop the typing.

i.e on scene unload.
Or on a button, note if the scene is still visible and the intervals are cleared, the text that has already been will remain but will not progress.


Update:

1.3.3 - 27-01-2023
•Removed Bullet characters in the comments as they could stop some export scripts working ??.

1.3.2 - 2018
•Fixed bug that stopped no cursor runs from completing. ( misplaced } ) and needed extra check on if blinker is running so we do not restart it by mistake at end of run.

•change to touchend. iOS seemed to show the keyboard and then hide. (need to investigate further)

•set the input div (iOS) to -200px top as it was showing through the Mobile Safai semi transparent menu bar

Note TypeTextExtension_v132_indent in a below post includes extra code for indents

1.3.1
•Put the blinker setInteval in a function so we can stop and start it. This allows us to set the speed for auto type to give a better affect.

•Added vertical-align:top to the blinker span. This sets the top of the span/cursor to the top of the parent div. This helps stop jumping of the text as the span will try to adjust the size of the text line

•Added cursorVerticalAlign: option to the cursor options. This allow for use manual control of vertical-align of the cursor

•Added cursorLineHeight: option to the cursor options. this allow for use manual control of line-height of the cursor

1.3.0 •removed the need for jquery, Change Cursor options mapping

3 Likes