Event of JS&jQuery interactive web front end development

Posted by Typer999 on Mon, 10 Feb 2020 10:35:23 +0100

Article directory

6 incident

6.1 event handling: the process of event triggering JavaScript

1) process

  • Select element, specify event, call code
  • Example: blur event on username

2) Binding events to elements

  • HTML event handler (not recommended)

    • Earlier versions of HTML contained a set of attributes in response to events for the element to which it belonged
    • The name of the property corresponds to the name of the event, and the value of the property corresponds to the name of the function to be run when the event occurs
    • For example, <a onclick= "hide (") >, the user clicks the <a> element and calls the hide() method.
    • Example:
      • event-attributes.js:
        function checkUsername(){
        	var elMsg = document.getElementById('feedback');
        
        	//Get the feedback element
        	var elUsername = document.getElementById('username');
        	//Get user name input
        	if(elUsername.value.length<5){
        		//If the user name is too short, set the prompt message
        		elMsg.textContent = 'User name should not be less than 5 characters!';
        	}else{
        		//Otherwise, clear the information
        		elMsg.textContent = '';
        	}
        }
        
      • event-attributes.html:
        <!DOCTYPE html>
        <html lang="en">
        <head>
        	<meta charset="UTF-8">
        	<title>event-attributes</title>
        </head>
        <body>
        	<form method="post" action="http://www.example.org/register">
        		<label for="username">User name: </label>
        		<input type="text" id="username" onblur="checkUsername()" />
        		<div id="feedback"></div>
        
        		<label for="password">Password: </label>
        		<input type="password" id="password" />
        
        		<input type="submit" value="register">
        	</form>
        	<script type="text/javascript" src="event-attributes.js"></script>
        </body>
        </html>
        
      • It is displayed as:

  • Traditional DOM event handler

    • Event handlers better than HTML
    • For all major browsers
    • Only one function can be attached to an event
    • Example: (no onblur event attribute in html file)
      //Define named functions
      function checkUsername(){
      	//Function to check user name length
      }
      //Saving references to DOM elements with variables
      var el = document.getElementById('username');
      //The last line of event handler el.onblur: indicates waiting for the onblur event to occur on the element corresponding to the variable el
      el.onblur = checkUsername;     //Remove the curly brackets to prevent the code from running before the event
      
  • Event listener

    • Allow one event to trigger multiple methods
    • Syntax: element. Addeventlistener (event, code, event flow);
      • Three parameters of addEventListener(): the event to be listened to, the code to be executed when the event occurs, and a Boolean value (usually false)
      • removeEventListener(): remove event listener
    • Example:
      //Define named functions
      function checkUsername(){
      	//Function to check user name length
      }
      //Saving references to DOM elements with variables
      var el = document.getElementById('username');
      //The last line of event handler el.onblur: indicates waiting for the onblur event to occur on the element corresponding to the variable el
      el.addEventListener('blur',checkUsername,false)     //Remove brackets
      
  • Using parameters

    var elUsername = document.getElementById('username');
    var elMsg = document.getElementById('feedback');
    
    function checkUsername(minLength){
    	if(elUsername.value.length<minLength){
    		//If the user name is too short, set the prompt message
    		elMsg.textContent = 'User name should not be less than'+minLength+'A character!';
    	}else{
    		//Otherwise, clear the information
    		elMsg.textContent = '';
    	}
    }
    
    elUsername.addEventListener('blur',function(){
    	//Transfer parameters	
    	checkUsername(3);
    })
    
  • Support old version of IE browser (IE5 ~ IE8)

    • attachEvent() method:
    • Check if the browser supports the addEventListener() method
      if(el.addEventListener){
      	//If the addEventListener method is supported
      	el.addEventListener('blur',function(){
      		checkUsername(5);
      },false);
      }else{
      	//If the addEventListener method is not supported
      	//Event name prefixed with on
      	el.attachEventListener('onblur',function(){
      		checkUsername(5);
      	});
      }
      

3) Event flow

  • The order in which events occur is called the "event flow"
  • Two directions
    • The last parameter of the addEventListener() method allows you to select the direction of event triggering: true for capture, false for bubble
    • Event bubbling: events propagate from the most specific node to the widest node (supported by most browsers)
    • Event capture: events are propagated from the widest node to the most specific node (not supported by IE8 and earlier)

4) Event object

  • When an event occurs, the event object contains some information about the event and which element it occurs on

  • Function that the event object is passed as an argument to any event handler / event listener

  • Event listener without parameters

    function checkUsername(e){
    	var target = e.target;       //Get the target of the event
    }
    var el = document.getElementById('username');
    el.addEventListener('blur',checkUsername,false);
    
  • Event listener with parameters

    function checkUsername(e,minLength){
    	var target = e.target;       //Get the target of the event
    }
    var el = document.getElementById('username');
    //The reference of the event object is automatically passed to the anonymous function as the first parameter of the named cold and summer
    el.addEventListener('blur',function(e){       
    	checkUsername(e,5);     //Named function receives a reference to the event object passed in as the first argument
    },false);
    
  • Event listener syntax for IE5 to IE8

    attribute IE5 to IE8 target
    target srcElement The target of the event (the specific element that interacts with the user)
    ype type Event type
    ancelable I won't support it Can I undo the default behavior of an event on this element
    Method IE5 to IE8 target
    reventDefault() returnValue Undo the default behavior of this event
    topPropagation() cancelBubble Stop event continue bubbling / capture down
  • Event objects in IE5-IE8

    • Functions that are not automatically passed to the event handler / listener, but exist as a child property of the window object
      //Get attribute: method of using short circuit value
      var target = e.target||e.srcElement;
      
      //Function to get the event target
      function getEventTarget(e){
      	//Check whether the event object is passed to the function
      	if(!e){
      		//In IE8 and earlier, parameter e did not save any objects
      		//Set e as the event sub object of the window object
      		e = window.event;
      	}
      	return e.target||e.srcElement;
      }
      
  • Example: using event objects in event listeners

    • This function has more flexibility: it can be used to detect the length of content in any text input box, and it can also run in IE8 and earlier versions
    //Declaring function
    function checkLength(e,minLength){
    	var el,elMsg;
    	if(!e){
    		e = window.event;
    	}
    	//Get the element the user is interacting with
    	el = e.target||e.srcElement;
    	elMsg = el.nextSibling;
    
    	if(el.value.length < minLength){
    		elMsg.innerHTML = 'User name should not be less than'+minLength+'Character';
    	}else{
    		elMsg.innerHTML = '';
    	}
    }
    
    var elUsername = document.getElementById('username');
    if(elUsername.addEventListener){       //If event listener is supported
    	elUsername.addEventListener('blur',function(e){
    		checkLength(e,5);
    	},false);
    }else{                                 //otherwise
    	elUsername.attachEvent('blur',function(e){
    		checkLength(e,5);
    	});
    }
    
  • Event delegation

    • Place the event handler on a container element and use the target attribute of the event object to find the descendants of the event
    • advantage
      • Apply to new elements
      • Solve the limitation of this keyword
      • Simplified code, easy to maintain
  • Change default behavior

    • preventDefault()
      • Function: prevent the default behavior of the element (for example, click Submit Form to stay on the current page instead of jump to a new page)
      • IE8 and earlier: use returnValue = false
        //Check if the preventDefault() method is supported
        if(event.preventDefault){
        	event.preventDefault();
        }else{ 
        //Not supported, use IE8
        	event.returnValue = false;
        }
        
    • stopPropagation()
      • Function: prevent an event from bubbling to its ancestor elements
      • IE8 and earlier: use cancelBubble = true
        //Check if stopPropagation() method is supported
        if(event.stopPropagation){
        	event.stopPropagation();
        }else{ 
        //Not supported, use IE8
        	event.cancelBubble = true;
        }
        
    • Use at the same time: return false;
      • Prevents the default behavior of the element and the event from bubbling up or down
      • Can run in all browsers
      • After the interpreter encounters the return false statement, it stops executing the following code and continues to execute the content after calling the function
  • Example: use event delegation (each list item contains a link, which is removed from the list when the user clicks the link)

    • delegation.html
      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>delegation</title>
      </head>
      <body>
      	<ul id="shoppingList">
      		<li class="complete"><a href="itemDone.php?id=1"><em>fresh</em>figs</a></li>
      		<li class="complete"><a href="itemDone.php?id=2">pine nuts</a></li>
      		<li class="complete"><a href="itemDone.php?id=3">honey</a></li>
      		<li class="complete"><a href="itemDone.php?id=4">vinegar</a></li>
      	</ul>
      </body>
      </html>
      
    • delegation.js
      //Get the elements the user clicks on
      function getTarget(e){
      	if (!e) {
      		e = window.event;
      	}
      	return e.target||e.srcElement;
      }
      
      function itemDone(e){
      	//Remove list item
      	var target,elParent,elGrandparent;
      	target = getTarget(e);      //Get clicked links
      	elParent = target.parentNode;      //Get the list item
      	elGrandparent = target.parentNode.parentNode;    //Get the list
      	elGrandparent.removeChild(elParent);       //Remove the list item
      
      	//Block default behavior: click the link to jump to another page
      	if(e.preventDefault){
      		e.preventDefault();
      	}else{
      		e.returnValue = false;
      	}
      }
      
      //Set event listener: call itemDone() on Click
      var el=document.getElementById('shoppingList');
      if(el.addEventListener){
      	el.addEventListener('click',function(e){
      		itemDone(e);
      	},false);
      }else{
      	el.attachEvent('onclick',function(e){
      		itemDone(e)
      	});
      }
      
    • Operation result
      • Original page
      • Click on the second item
  • Identify the element where the event occurred

    • Method 1: target attribute of event object
    • Method 2:this keyword
      • This method is valid when no parameters are passed to the function
        function checkUsername(){
        	var elMsg = document.getElementById('feedback');
        	if(this.value.length<5){             //this keyword points to the element where the event occurred
        		elMsg.innerHTML = 'User name is not long enough!';
        	}else{
        		elMsg.innerHTML = '';
        	}
        }
        
        var el = document.getElementById('username');
        el.addEventListener('blur',checkUsername,false);
        
      • this keyword fails when a parameter is passed to a function
        • The owner of the function is no longer an element bound by the event listener, but an anonymous function
        • You need to pass the event element as an argument to the function
        function checkUsername(e,minLegnth){
        	var elMsg = document.getElementById('feedback');
        	if(this.value.length<minLength){
        		elMsg.innerHTML = 'User name is not long enough!';
        	}else{
        		elMsg.innerHTML = '';
        	}
        }
        var el = document.getElementById('username');
        el.addEventListener('blur',function(){
        	checkUsername(e,5);
        },false);
        

6.2 using different event types

  • W3C DOM events
  • HTML5 events: the HTML5 specification specifies HTML related events that browsers should support
  • BOM incident

1) User interface (UI) events

  • Main UI events

    Event Explain Browser support
    load web page loading completed Attach to window object
    unload web page loading Attach to window object
    error Browser encountered JavaScript error / there is a non-existent resource Different browsers have different situations, so it's hard to rely on this method for error handling
    resize Browser window size changes Events are triggered continuously when the browser window is resized (avoid using complex code in this event trigger)
    scroll Users use scrollbars to move pages Events are triggered continuously as the window Scrolls (avoid using complex code in this event trigger)
  • Event handlers / listeners for UI events are attached to the browser window

  • Example: after the page is loaded, set the input focus in the text box

    • .html
      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Document</title>
      </head>
      <body>
      	<div>
      		<p>User name:</p>
      		<input type="text" id="username">
      	</div>
      	<script src="example.js"></script>
      </body>
      </html>
      
    • .js
      //The setup() function is not valid until the page is loaded because it needs to find the element corresponding to the id attribute and set the focus to it
      function setup(){
      	var textInput  = document.getElementById('username');  //Get text box
      	textInput.focus();          //Focus text box
      }
      
      window.addEventListener('load',setup,false);    //Event listener attached to window object
      
    • Run result: the text box gets the input focus after the page is loaded

2) Focus event

  • Main focus events

    Event Explain Event stream
    focus Element gets focus capture
    blur Element out of focus capture
    focusin Same as focus Bubbling, trapping
    focusout Same as blur Bubbling, trapping
  • Applicable scenarios (in the form)

    • Display prompt or feedback information when users interact with independent elements in the form
    • Trigger form validation when a user moves from one space to another control
  • Example: when the text box gets or loses focus, different feedback information is displayed under the input box

    • .html

      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Document</title>
      	<link rel="stylesheet" href="css.css">
      </head>
      <body>
      	<p>User name:</p>
      	<input type="text" id="username">
      	<div class="feedback" id="feedback">feedback</div>
      	<script src="focus-blur.js"></script>
      </body>
      </html>
      
    • .css

      .tip{
      	color: pink;
      }
      .feedback{
      	color: gray;
      }
      .warning{
      	color: red;
      }
      
    • .js

      //Declaration function checkUsername: triggered when the text box loses focus, to check whether the user name length is sufficient
      function checkUsername(){
      	var username = el.value;
      	if (username.length < 5) {
      		elMsg.className = 'warning';
      		elMsg.textContent = 'User name is too short!';
      	}else{
      		elMsg.textContent = '';
      	}
      }
      //Declare function tipUsername: triggered when the text box gets focus, modify the class attribute of the element, and update the content of the element
      function tipUsername(){
      	elMsg.className = 'tip';
      	elMsg.textContent = 'User name should not be less than 5 characters!';
      }
      
      //Get elements
      var el = document.getElementById('username');
      var elMsg = document.getElementById('feedback');
      
      //Set up event listener
      el.addEventListener('focus',tipUsername,false);
      el.addEventListener('blur',checkUsername,false);
      
    • Operation result

      • Original page
      • Enter the user name and call the tipUsername() method
      • Lose focus, call checkUsername() method
      • Enter a user name that meets the requirements

3) Mouse events

  • All elements in the page support mouse events, which will bubble and propagate

  • Main mouse events (different on touch screen devices)

    Event Explain touch
    click The user presses and releases a key on the same element Tap screen = left click
    dbclick The user presses and releases a key twice in a row on the same element Tap the screen twice = double click with the left mouse button
    mousedown User presses key on an element Using the touchstart event
    mouseup User releases key on an element Using touchend events
    mousemove User moves mouse Triggered when the pointer moves over an element
    mouseover User moves mouse over an element Triggered when the pointer moves out of an element
    mouseout User moves the mouse away from an element Triggered when the pointer moves
  • Reasons for separating mousedown and mouseup

    • Two events handle mouse press and release actions respectively
    • It is usually used to implement drag and drop function or to develop game control
  • Example: remove the large label added to the screen through the click event

    • .html

      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Document</title>
      </head>
      <body>
      	<script src="click.js"></script>
      </body>
      </html>
      
    • .js

      var msg = '<div class=\"header\"><a id=\"close\" href="#"> close X </a></div>';
      msg += '<div><h2>system maintenance</h2>';
      msg += 'our servers are being updated between 3 and 4 am';
      msg += 'during this time...</div>';
      
      var elNote = document.createElement('div');       //Create a new element
      elNote.setAttribute('id','note');         //Add id attribute
      elNote.innerHTML = msg;            //Add information
      document.body.appendChild(elNote);     //Add to page
      
      function dismissNote(){
      	document.body.removeChild(elNote);        //Removing Elements
      }
      
      var elClose = document.getElementById('close');     //Get links that have been added to the page
      
      elClose.addEventListener('click',dismissNote,false);      //Listens to click events, and then calls dismissNote() method after clicking.
      
    • Operation result

      • Click the blue link to clear the page
  • Where the event occurs: the event object contains the location information of the mouse pointer

    • screen
      • Screen x, screen properties: the position of the display pointer in the whole display, calculated from the top left corner of the screen (not the browser)
    • page
      • pageX, pageY properties: display the position of the pointer in the whole page
      • The top of the page may be outside the visible area, so even if the mouse pointer is in the same location, the page and client coordinates may be different
    • Client
      • clientX, clienY properties: display the position of the pointer in the whole browser visual area
      • Client coordinates are not affected even if the top of the page is beyond the visible area
  • Example: when moving the mouse on the screen, the text box above the page updates the mouse position information

    • .html
      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Document</title>
      </head>
      <body>
      	<div class="body" id="body">
      		<div>screenX: <input type="text" id="sx"></div>
      		<div>screenY: <input type="text" id="sy"></div>
      		<div>pageX: <input type="text" id="px"></div>
      		<div>pageY: <input type="text" id="py"></div>
      		<div>clientX: <input type="text" id="cx"></div>
      		<div><clientY: <input type="text" id="cy"></div>
      	</div>
      	<script src="position.js"></script>
      </body>
      </html>
      
    • .js
      var sx = document.getElementById('sx');
      var sy = document.getElementById('sy');
      var px = document.getElementById('px');
      var py = document.getElementById('py');
      var cx = document.getElementById('cx');
      var cy = document.getElementById('cy');
      
      function showPosition(){
      	sx.value = event.screenX;
      	sy.value = event.screenY;
      	px.value = event.pageX;
      	py.value = event.pageY;
      	cx.value = event.clientX;
      	cy.value = event.clientY;
      }
      
      var el = document.getElementById('body');
      el.addEventListener('mouseover',showPosition,false);
      
    • Operation result

4) Keyboard events

  • Keyboard events

    Event Explain Additional explanation
    input Triggered when the value of the < input > < textarea > element changes In browsers prior to IE8, keypress events are used
    keypress Create a character (repeatedly triggered when pressing and holding) Occurs before characters appear on the screen
    keydown The first time the user presses a key (repeatedly triggered when pressed and held) Occurs before characters appear on the screen
    keyup User releases a key Occurs after characters are displayed on the screen
  • The sequence of keyboard events: keydown, keypress, keyup

  • keyCode property:

    • When using the keydown and keypress events, the event object has a keyCode attribute indicating which key the user has pressed
    • The keyCode property returns the ASCII code corresponding to the lowercase character of the key. If you want to get the specific character, use the built-in method String.fromCharCode(event.keyCode) of the String object
  • Example: the < textarea > element only contains 180 characters. When the user enters text, how many more characters can he input

    • .js
      var el;
      
      function charCount(){
      	var textEntered,charDisplay,counter,lastKey;
      	textEntered = document.getElementById('message').value;
      	charDisplay = document.getElementById('charactersLeft');
      	//Counter
      	counter = (180-(textEntered.length));
      	charDisplay.textContent = counter;      //Display the number of characters that can be input
      	//Operation on last character
      	lastKey = document.getElementById('lastkey');
      	lastKey.textContent = 'Of the last character ASCII Code:'+el.keyCode;
      }
      
      el = document.getElementById('message');
      el.addEventListener('keypress',charCount,false);
      

5) Form event

  • Form Events

    Event trigger
    input The values in < input > or < textarea > changed;
    Value changes in element with contentable attribute
    change Check box, radio box, radio button value change
    submit User submit form
    reset User clicks reset button
    cut User cuts content from a form field
    copy Users copy content from a form field
    paste Users paste content into a form field
    select User selects part of text in a form field
  • Verification: check the value of the form

  • Example: using the keyboard event keypress

    • .js
      //Declare variables
      var elForm,elSelectPackage,elPackageHint,elTerms,elTermsHint;
      elForm = document.getElementById('formSignup');     //Storage element
      elSelectPackage = document.getElementById('package');
      elPackageHint =document.getElementById('packageHint');
      elTerms = document.getElementById('terms');
      elTermsHint = document.getElementById('termshint');
      
      //Declaration function: display the information of the selected candidate
      function packageHint(){
      	var package = this.options[this.selectedIndex].value;         //Get selected elements
      	if(package == 'monthly'){
      		//If you choose to pay by month
      		elPackageHint.innerHTML = 'Annual payment can save 10 yuan!';
      	}else{
      		//otherwise
      		elPackageHint.innerHTML = 'Wise choice!';
      	}
      }
      
      //Declaration function: check whether the user has checked "agreement terms"
      function checkTerms(event){
      	if(!elTerms.checked){
      		//If not checked
      		elTermsHint.innerHTML = 'You must agree to the terms!';
      		event.preventDefault();    //Prevent the default behavior of form elements: submit form data to the server
      	}
      }
      
      elForm.addEventListener('submit',checkTerms,false);         //Event listener
      elSelectPackage.addEventListener('change',packageHint,false);         //Event listener
      

6) Change event and change observer

  • When an element is added to or removed from the DOM, the structure of the DOM changes, triggering a change event

  • Change event

    Event Explain
    DOMNodeInserted A node is inserted as a direct child of another node;
    For example, when using appendChild(), replaceChild(), insertBefore()
    DOMNodeRemoved One node is removed from the other;
    For example, when using removeChild(), replaceChild()
    DOMSubtreeModified Document changes
    DOMNodeInsertedIntoDocument One node is inserted as a descendant of another
    DOMNodeRemovedFromDocument A node is removed from the ancestor node
  • Change observer

    • Disadvantages of change events
      • When the script modifies the page too much, it will trigger many change events, which may cause the page to slow down or even lose response
      • Events propagate in DOM, triggering more change events
    • Design concept: wait for the script to finish all the work before responding, and then report the changes of DOM to the script in batch
    • Browser support
      • IE11,Firefox14,Chrome27,Safari6.1,Opera15
      • Mobile browser: Safari on Android 4.4 and IOS 7
  • Example: using change events

    • .html
      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Document</title>
      </head>
      <body>
      	<div id="list">
      		<li>This is a list item</li>
      	</div>
      	<a href="">Click to add a new list item</a>
      	<div id="counter"></div>
      	<script src="mutation.js"></script>
      </body>
      </html>
      
    • .js
      var elList,addLink,counter;
      var newEl,newText,listItems;
      
      elList = document.getElementById('list');
      addLink = document.querySelector('a');
      counter = document.getElementById('counter');
      
      //Declare function: click the link to add a new list item to the list
      function addItem(e){
      	e.preventDefault();      //Default behavior to block clicking links
      	newEl = document.createElement('li');    //Create li element
      	newText = document.createTextNode('New list item');      //Set text content for li element
      	newEl.appendChild(newText);         //Add to li element
      	elList.appendChild(newEl);      //Add li element to list
      }
      
      //Declare function: displays the number of list items after inserting new elements
      function updateCount(){
      	listItems = list.getElementsByTagName('li').length;
      	counter.innerHTML = 'Number of list items:'+listItems;
      }
      
      addLink.addEventListener('click',addItem,false);      //Listen for click events: add new elements after clicking the link
      elList.addEventListener('DOMNodeInserted',updateCount,false);        //Listen to the event of inserting an element: count the total number of elements after inserting an element
      
    • Operation result
      • Original page
      • Click link

7) HTML5 events

  • Major page level events
Event trigger Browser support
DOMContentLoaded DOM tree formation;
In this event, the script runs earlier than the load event to make the page appear to load faster
Chrome0.2,Firefox1,IE9,Safari3.1,Opera9
hashchange The value of the URL changes and is triggered on the window object;
After triggering, the event object saves the URL before and after the event through the oldURL newURL property
IE8,Firefox20,Safari5.1,Chrome26,Opera12.1
beforeunload Trigger on the window object before the page is unloaded Chrome1,Firefox1,IE4,Safari3,Opera12
  • The HTML5 specification introduces events that support the latest devices (mobile phones, tablets), which can

    • Response gesture
    • Based on the mobile scene brought by accelerometer (detecting the angle change of handheld device)
  • Example: using HTML5 events

    //Declare function: let text box get focus
    function setup(){
    	var textInput = document.getElementById('message');
    	textInput.focus();
    }
    
    //Listening event: when the DOM tree is just formed, let the text box get the focus
    window.addEventListener('DOMContentLoaded',setup,false);
    
    //Listening event: click submit to leave this page and check whether the user really wants to leave
    window.addEventListener('beforeunload',function(event){
    	return 'Your changes have not been saved!';
    },false);
    

6.3 example: users record voice notes

  • The user can enter a name to display in the page header, and then press the recording key to change the displayed picture at the same time
  • .js
    var username,noteName,textEntered,target;
    
    username = document.getElementById('username');
    noteName = document.getElementById('noteName');     //Save element of label
    	
    //Declaration function: copy text from the form input box and update the page header content
    function writeLabel(e){
    	if(!e){
    		e = window.event;
    	}
    	target = event.target||event.srcElement;     //Get event target
    	textEntered = e.target.value;     //Element value
    	noteName.textContent = textEntered;    //Update label content
    }
    
    //Event listener: displays user input in a text box in the page header
    if (document.addEventListener) {
    	document.addEventListener('click',function(e){
    		recorderControls(e);      
    	},false);
    	username.addEventListener('input',writeLabel,false);
    }else{
    	document.attachEvent('onclick',function(e){
    		recorderControls(e);
    	});
    	username.attachEvent('onkeyup',writeLabel);
    }
    
    
    //Declaring functions: the default behavior of blocking links
    function recorderControls(e){
    	if (!e) {
    		e = window.event;
    	}
    	target = event.target||event.srcElement;    //Get target element
    	if (event.preventDefault) {
    		e.preventDefault;
    	}else{
    		event.returnValue = false;
    	}
    }
    
    //Which function is called depends on whether the user wants to record or stops recording
    switch(target.getAttribute('data-state')){
    	case 'record':
    		record(target);
    		break;
    	case 'stop':
    		stop(target);
    		break;
    }
    
    //Declare function: start recording
    function record(target){
    	target.setAttribute('data-state','stop');
    	target.textContent = 'stop';
    }
    
    //Declare function: stop recording
    function stop(target){
    	target.setAttribute('data-state','record');
    	target.textContent = 'record';
    }
    
Published 6 original articles, won praise 0, visited 141
Private letter follow

Topics: Attribute html5 Javascript less