jQuery Code Sample


(function($) {

	///////////////////////////////////////
	// INIT
	///////////////////////////////////////
	
	//*-----Get Data from single-classes.php in theme folder twentyfourteen-child folder-----*//
	
	var classData = pw_script_vars.data; //array of img snd text combinations from Web App plugin stored in SQL
	classData = JSON.parse(classData); //parse array to be readable by js
	var appType = pw_script_vars.activity; //text to identify activity type(app,video,flash cards, or quiz)
	var ajaxurl = pw_script_vars.ajaxurl; //url to admin-ajax
	var userID = pw_script_vars.userid; //text to identify user
	var classID = pw_script_vars.classid; //text to identify user
	var startS = 0;
	var complete = 0;
	//*-----start to build the page-----*//
	
	var htmlStructure = '\
    <div class="gridContainerApp clearfix statusText">\
        <div class="fluid leftApp">\
            <div id="object1">\
                <div class="objectImage" >\
                    <img >\
                    <div class="objectImageList">\
                        <ul id="object1List">\
                            <li></li><li></li><li></li><li></li>\
                        </ul>\
                    </div>\
                </div>\
                <input class="input" type="text">\
            </div>\
        </div>\
        <div class="fluid rightApp">\
            <div id="object2">\
                <div class="objectImage" >\
                    <img>\
                    <div class="objectImageList">\
                        <ul id="object2List">\
                            <li></li><li></li><li></li><li></li>\
                        </ul>\
                    </div>\
                </div>\
                <input class="input" type="text">\
            </div>\
        </div>\
    </div><br clear="all" />\
    <div class="gridContainerApp clearfix statusText">\
        <div class="fluid leftApp">\
            <div id="object3">\
                <div class="objectImage" >\
                    <img>\
                    <div class="objectImageList">\
                        <ul id="object3List">\
                            <li></li><li></li><li></li><li></li>\
                        </ul>\
                    </div>\
                </div>\
                <input class="input" type="text">\
            </div>\
        </div>\
        <div class="fluid rightApp">\
            <div id="object4">\
                <div class="objectImage" >\
                    <img>\
                    <div class="objectImageList">\
                        <ul id="object4List">\
                            <li></li><li></li><li></li><li></li>\
                        </ul>\
                    </div>\
                </div>\
                <input class="input" type="text">\
            </div>\
        </div>\
    </div><br clear="all" /><a href="#" id="next">next</a>';
	
	startApp(); 
	
	
	///////////////////////////////////////
	// FUNCTIONS
	///////////////////////////////////////
	
	//*-----UTILITY FUNCTIONS-----*//
	
	///SHUFFLE ARRAY	
	function shuffleArray(array) {
            for (var i = array.length-1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
            return array;
	}
	///Add Source to Audio Element
	function addSource(elem, path, type) {
        path = 'https://learnenglishcloud.com/wp-content/plugins/Web-App/assets/snd/'+ path;
        $('<source>').attr({src:path, type:type}).appendTo(elem);
    }
    ///Add Source to Audio Element
	function addImageSource(path) {
        path = 'https://learnenglishcloud.com/wp-content/plugins/Web-App/assets/img/'+ path;
        return path;
    }
    ///Audio ShortCode
	function appAudio(object,elem){
        //Set-up Audio
        var audio = $('<audio>', {id : object.text.replace(/\.| /g,'')},'</audio>');
        var source = addSource(audio, object.sound, 'audio/mpeg');		
        audio.text(source);
		//addSource(audio, 'audioFile.ogg','audio/ogg');
        //addSource(audio, 'audioFile.mp3', 'audio/mpeg');
        audio.appendTo($('#object'+elem));
	}
	
	//*----- APP-----*//
	
	///Initialize the App building process
	function startApp(){		
		classData = shuffleArray(classData); //class data is shuffled and ready for use	
		runApp(classData,startS); //create html structure and attach ALL events/data to elements	
	}
	///Run App Data
	function runApp(data,start){
        //complete = 1;	//testing only, skips class and runs user meta update 
        if (complete == 1){
            var callVars = {
                'action' : 'class_complete',
                'class' : classID,
                'type' : appType,
                'id' : userID
            };	
            // AJAX call to function.php file via admin-ajax.php
            jQuery.post(ajaxurl, callVars, function(response) {
                alert('Got this from the server: ' + response);
            });
            alert('GREAT JOB :)');
            window.location.href = "https://learnenglishcloud.com/learn-english/";		
        }else{
            //Create Basic HTML structure
            $('#activity').html(htmlStructure);
            var objNum = 1;
            var object1;		
            var object2;
            var object3;
            var object4;
            var objectCurrent = [];
            for (i = 0; i < 4; i++) {
                if (data[start] === undefined){
                    console.log('NO WHERE TO GO');
                    start = Math.floor(Math.random() * 10) + 1;			
                    objectCurrent.push(data[start]);
                    console.log(i+' / '+start);	
                    console.log(data[start]);
                    complete = 1;	
                }else{
                    objectCurrent.push(data[start]);
                }
                start++;
            }
            startS = start;	
            console.log(startS);
            $.each( data, function( key, value ) {
                switch(objNum) {
                    case 1: object1 = value; break;
                    case 2: object2 = value; break;
                    case 3: object3 = value; break;
                    case 4: object4 = value; break;
                }
                objNum++;				
            });
            //Adding All List Items
            var nthArrShuffle = shuffleArray([1,2,3,4]);		
            $('#object1List>li:nth-child('+nthArrShuffle[0]+')').append('<a href="#">'+objectCurrent[0].text+'</a>');
            $('#object1List>li:nth-child('+nthArrShuffle[1]+')').append('<a href="#">'+objectCurrent[1].text+'</a>');
            $('#object1List>li:nth-child('+nthArrShuffle[2]+')').append('<a href="#">'+objectCurrent[2].text+'</a>');
            $('#object1List>li:nth-child('+nthArrShuffle[3]+')').append('<a href="#">'+objectCurrent[3].text+'</a>');
            $('#object2List>li:nth-child('+nthArrShuffle[0]+')').append('<a href="#">'+objectCurrent[0].text+'</a>');
            $('#object2List>li:nth-child('+nthArrShuffle[1]+')').append('<a href="#">'+objectCurrent[1].text+'</a>');
            $('#object2List>li:nth-child('+nthArrShuffle[2]+')').append('<a href="#">'+objectCurrent[2].text+'</a>');
            $('#object2List>li:nth-child('+nthArrShuffle[3]+')').append('<a href="#">'+objectCurrent[3].text+'</a>');
            $('#object3List>li:nth-child('+nthArrShuffle[0]+')').append('<a href="#">'+objectCurrent[0].text+'</a>');
            $('#object3List>li:nth-child('+nthArrShuffle[1]+')').append('<a href="#">'+objectCurrent[1].text+'</a>');
            $('#object3List>li:nth-child('+nthArrShuffle[2]+')').append('<a href="#">'+objectCurrent[2].text+'</a>');
            $('#object3List>li:nth-child('+nthArrShuffle[3]+')').append('<a href="#">'+objectCurrent[3].text+'</a>');
            $('#object4List>li:nth-child('+nthArrShuffle[0]+')').append('<a href="#">'+objectCurrent[0].text+'</a>');
            $('#object4List>li:nth-child('+nthArrShuffle[1]+')').append('<a href="#">'+objectCurrent[1].text+'</a>');
            $('#object4List>li:nth-child('+nthArrShuffle[2]+')').append('<a href="#">'+objectCurrent[2].text+'</a>');
            $('#object4List>li:nth-child('+nthArrShuffle[3]+')').append('<a href="#">'+objectCurrent[3].text+'</a>');
            //Adding Images to Object Containers
            $('#object1>.objectImage>img').attr('src', addImageSource(objectCurrent[0].image));
            $('#object2>.objectImage>img').attr('src', addImageSource(objectCurrent[1].image));
            $('#object3>.objectImage>img').attr('src', addImageSource(objectCurrent[2].image));
            $('#object4>.objectImage>img').attr('src', addImageSource(objectCurrent[3].image));
            //Adding Names to Object Containers
            $('#object1>input').attr('name', objectCurrent[0].text);
            $('#object2>input').attr('name', objectCurrent[1].text);
            $('#object3>input').attr('name', objectCurrent[2].text);
            $('#object4>input').attr('name', objectCurrent[3].text);
            //Adding Sound to Object Containers
            appAudio(objectCurrent[0],1);
            appAudio(objectCurrent[1],2);
            appAudio(objectCurrent[2],3);
            appAudio(objectCurrent[3],4);
        }
	}
	///Hide all word lists in App
	$('.objectImageList').hide();
	///Event: click input will toggle word list
	$('body').on( 'click', 'input', function () {
		$('input').prev().children('.objectImageList').hide('fast');
		$(this).prev().children('.objectImageList').animate({ height: 'toggle', opacity: 'toggle' }, 'slow');
	});
	///Event: Input keyup check in object name matches user input	
	$('body').on( 'keyup', '.input', function() {
        if ( $(this).attr('name') == $(this).val() ){
            $(this).css('background-color','rgb(144, 238, 144)');
            $('#'+$(this).attr('name').replace(/\.| /g,'')).get(0).play();
        }else{
            $(this).css('background-color','rgb(255, 255, 255)');
        }
	});
	///Event: click a word in the word list and play corresponding sound	
	$('body').on('click', '.objectImageList>ul>li', function () {
		$('#'+$(this).text().replace(/\.| /g,'')).get(0).play();//test
		return false;
	});
	///Event: click next and check if all answers are right, if so move to next sequence
	$('body').on('click', '#next', function () {	
        var empty = 0;
        $(".gridContainerApp").find(".input").filter(function() {
            if ($(this).css('background-color') == 'rgb(255, 255, 255)' || $(this).css('background-color') == 'rgb(255, 95, 95)'){
                empty ++;
            } else {
                empty --;
            }
        });
        console.log(empty);
        if(empty == -4) {
            console.log('launching new startS'+startS);
            $('#activity').empty();
            runApp(classData,startS);
            $('.objectImageList').hide();
        } else {
            $(".gridContainerApp").find(".input").filter(function() {
                if ($(this).css('background-color')=='rgb(255, 255, 255)'){
                    $(this).css('background-color', 'rgb(255, 95, 95)');
                }
            });        
        }       
        return false;
    });


})(jQuery);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>