Skip to content

Instantly share code, notes, and snippets.

@OfTheDelmer
Last active December 25, 2015 01:19
Show Gist options
  • Save OfTheDelmer/6893967 to your computer and use it in GitHub Desktop.
Save OfTheDelmer/6893967 to your computer and use it in GitHub Desktop.

Javascript/JQuery workout

Exercises for fun

ex_1.js

Using only js

  • Create a square that's 20 percent the width and height of the document. Color it rgb(255,0,0).
  • If the square is 20 percent of the page width and height centering it would require 40 percent margin's on the left/right and top/bottom.

ex_1_b.js


Addding JQuery

  • Add an event that watches for a resize on the window and changes the square back to 20 percent with jQuery.

ex_1_c(Extra Fun)


Try the following individually:

$('div').css('-webkit-transform', 'rotateZ(30deg)');
  $('div').css('-webkit-transform', 'rotateY(30deg)');
  $('div').css('-webkit-transform', 'rotateX(30deg)');

Try the following individually:

 $('div').css('-webkit-transform', 'translateX(100px)');
 $('div').css('-webkit-transform', 'translateY(90px)');

ex_1_d


Try the following code in the web console and mouse over your window.

var mouseX, mouseY;
$(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
	console.log(mouseX);
	console.log(mouseY);
})

Could you use something like this to make a div follow your cursor?


ex_2

Bubble Trouble!

html

<div class="bubble">
	<div class="bubble">
		<div class="bubble">
			<div class="bubble">
			
			</div>
		</div>
	</div>
</div>

Style

<style>
	.bubble{
		position: inherit;
		background-color: blue; 
		padding: 20px,
		border: solid 5px white;
	}	
</style>

JS

Get all the bubbles

bubbles = document.getElementsByClassName("bubble")

Attach a click event to each bubble

for( var i = 0; i < bubbles.length; i++){ 	
	bubbles[i].onclick = function(event){
	 this.style.backgroundColor = "red"
	}
}

If you click the inner most div you'll notice it propagates to all the bubbles containing it. Hint "event.stopPropogation"

Change it so that only the current bubble is changed


ex_3

Interactive lists

<form>
	<input type="text">
</form>

<ul id="myList">
	

</ul>

JS

// 1.) Watch for a submit event
$('form').on('submit', function(){
	... 
	
	// 2.) Get the input from the input tag
	$myInput = // … some jQuery here…  
	
	 
	//	3.) Add `myInput` to `#myList`,
	 

	/* 
		4. ) Add a click event 
			 to the appended element
			 that changes the css when 
			 clicked
	*/
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment