Difference between revisions of "JQuery & DOM manipulations"

From Publication Station
 
Line 272: Line 272:




=Example=
=More examples=
* simple image gallery https://codepen.io/PublicationStation/pen/qYZPbB
 
==Interacting with special keys (r, Enter) of the Keyboard==
==Interacting with special keys (r, Enter) of the Keyboard==



Latest revision as of 10:21, 5 May 2018

jQuery

What is jQuery

jQuery is a JavaScript library makes programming interactive websites with Javascript, a lot simpler.

There are many JavaScript libraries, that make certain aspects of programming in JS easier - e.g. working with SVG, maps, making visualizations, etc, etc.

jQuery is on of the most popular and general purpose JavaScript libraries

http://jquery.com/

JS, made easy

Like with JS you can use jQuery to:

  • change HTML content
  • change element attributes
  • change an element style
  • retrieve the window size
  • listen to an even (e.g. a mouse click)
  • make a timer
  • validate data

But jquery makes your life to much easier, let's see how!

Structure

I will introduce jQuery in 3 steps:

  • What elements are manipulated? - jQuery selectors
  • How are elements manipulated? - jQuery manipulation
  • When are elements manipulated? - jQuery listeners

Loading jQuery library

jQuery is simply an external JavaScript file that you load on to your HTML page.

There are different ways to load it, inside the HTML <head></head> with::

 <head> 
 <script src="jquery-1.11.3.min.js"></script>
 </head>
  • Load it from online resource (CDN)
 <head>
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
 </head>

loading your code

Once you loaded the jQuery library (file), you need to load your jQuery code.

the most secure way, that ensures the code is run only after all the contents from the page are loaded is:

<script>
$(document).ready(
    function(){
      //your jQuery/JS code goes here
    })
</script>



What elements are manipulated? - jQuery selectors

http://api.jquery.com/category/selectors/

In order to change or retrieve HTML elements' content, attributes, style, we need to select those element(s) precisely. jQuery selector methods are masters at that.

simple selectors

  • element selector: $('h1') will select all the heading1 elements.
  • id selector: $('#large') will select the element with id large.
  • class selector: $('.small') will select all the elements with class small.

See code in Codepen:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  </head>
<body>
<h1>I am a <u>h1</u></h1>
<p id="large">I am p#large and will become large</p>
<p class="rotate">I am p.rotate and will tilt</p>
<h2 class="rotate">I am a h2.rotate and even I will shift position</h2>

<script>
$(document).ready(
    function(){
    $('h1').text('Yes, your a h1');
    $('#large').css('font-size', '50pt');
    $('.rotate').css('transform', 'skew(0deg, 5deg)');  
    })
</script>
</body>
</html>

advanced selectors

  • Descendant selectors: $('ul a') will select all a tags inside the ul tags.
  • Child selectors: $('ul > li') will select all li tags that are direct children from the ul tags.
  • Attribute selectors: $('img[src="img.jpg"]') will select all imgs that have as src the image img.jpg.

Attribute selectors example

See code in Codepen: https://codepen.io/PublicationStation/pen/OOwGWd

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<style>
    img { display: block;
          transition-duration:4s;}
</style>
  </head>
<body>
<img src="http://i.giphy.com/EsYu229wwE9R6.gif" name="lpb" />
<img src="http://i.giphy.com/5WUH6YDabP7hK.gif" />
<img src="http://i.giphy.com/CVHyjsVMGPqq4.gif" name="lpb" />
<img src="http://i.giphy.com/10HegwKCnl0krS.gif" />
<img src="http://i.giphy.com/CDMz3fckRXXDG.gif" />
<img src="http://i.giphy.com/9ZxHNOvMggGl2.gif" name="lpb" />
<img src="http://i.giphy.com/j50v9vd9rbhjG.gif" />
<img src="http://i.giphy.com/YP1hn6KUhDIgo.gif" />
<img src="http://i.giphy.com/VFzAK3xAaUCpW.gif" name="lpb" />
<img src="http://i.giphy.com/scGSxIFxfOkSs.gif" name="lpb" />
<img src="http://i.giphy.com/YP1hn6KUhDIgo.gif" />
<img src="http://i.giphy.com/zzGluVQkDjQXe.gif" />
<script>
$(document).ready(
    function(){
    $('img[name="lpb"]').css('transform', 'skewX(70deg)'); 
     //img[name="lpb"] will be skewed with
     
    })

</script>
</body>
</html>

How are elements manipulated? - jQuery manipulation

http://api.jquery.com/category/manipulation/

In the previous example we have already began manipulating the elements within the page, by using the jQuery method .css() and .text(). Let's look at them more in depth. Will be using example simple selectors.

  • .html()
    • read the html content of an element $('h1').html()
    • inserts html in the place of content
      $('p.rotate').html('<span style="background:red">replaces <i>html<i> contente</span>')
      
      and
  • .text()
    • like .html(), reads the content of an element, but disregards any contained html tags $('h1').text()
    • inserts text content of a tag $('h1').text('I am changing you')
  • .css()
    • reads values of css attributes $('.rotate').css('transform')
    • sets css attributes and values $('.rotate').css('transform', 'matrix(0.8, 0.02, 2, 5, 0, 0)').css('color', '#F205FF')
  • .attr()
    • reads the value of a attribute of $('head > script').attr('src') - reads the attribute source of script tag inside the head
    • sets elements' attributes $('*').attr('dir', 'rtl') - changes attribute dir (writing direction) from default(ltr) to rtl(right-to-left) for all the elements $('*') in the page

When are elements manipulated? - jQuery manipulation

http://api.jquery.com/category/events/

Actions like the page loading, moving a mouse, typing a key, or resizing the browser window are events that take place in the web page. For creating a interactive web-page, your scripts has to write to respond to events.

In the previous examples we already used 1 listener: $(document).ready() that is triggered with the whole page is loaded.

(lets use adventure time example:)

  • .click()
    • is triggered when the user clicks on the element:
$('img[name="lpb"]').click( 
    function(){ $(this).css('width', '250'); }
)
  • .mouseover()
$('img[name="lpb"]').mouseover( 
    function(){ $(this).css('width', '250'); }
)
  • .mouseout()
$('img[name="lpb"]').mouseout( 
    function(){ $(this).css('width', '500'); }
)
  • .resize()
$(window).resize(
     function(){$('body').prepend('<h1>resizing window</h1>')}
);


  • .keydown()
$('body').keydown(
  function(){ 
    var size = Math.random() * (4000 - 100) + 100; //random value btw 100-4000 
    $('img').css('width', size); //resize
    var deg = 'rotate('+(Math.random() * (360 - 0) + 0)+'deg)'; //random value btw 100-4000 
$('img').css('transform', deg); 
})


Example in codepen: https://codepen.io/PublicationStation/pen/EbpJLw

clicking evil cats: resize, add link;
<!DOCTYPE html>
<html>
  <head>
 <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  </head>
  <body>
    <h1>Content...</h1>
    <h1>for jQuery</h1>
    <h1></h1>  
    <p id="large">I am p#large and will become large</p>
 
    <p class="rotate">I am p.rotate and will tilt</p>
    <h2 class="rotate">I am a h2.rotate and even I will shift position</h2>
    <img class="rotate" src="" />
    <br/>
    <img src="https://dncache-mauganscorp.netdna-ssl.com/thumbseg/1619/1619140-bigthumbnail.jpg" />
    <img src="https://s-media-cache-ak0.pinimg.com/236x/35/98/76/359876a0f522051e747e878b9a6f551f.jpg" />
 
    <script>
      $(document).ready(function() {
        $("img").click(function() {
          var src = $(this).attr("src");
          $(this)
            .css("height", "100px")
            .after("<a href='" + src + "'>link</a>");
        });
      });
    </script>
  </body>
</html>

$(this)

in .click() you probably saw a new jQuery selector: $(this)

$(this) address the element that is under "focus".

For example:

$('img').click(
  function(){
    alert( 'This gif url is ' + $(this).attr('src'))
})


More examples

Interacting with special keys (r, Enter) of the Keyboard

Example in Codepen: https://codepen.io/PublicationStation/pen/WXKWLQ

<!DOCTYPE html>
<html>

<head>
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<body>
  <h1>Content...</h1>
  <h1>for jQuery</h1>
  <h1></h1>
  <p id="large">I am p#large and will become large</p>

  <p class="rotate">I am p.rotate and will tilt</p>
  <h2 class="rotate">I am a h2.rotate and even I will shift position</h2>
  <img class="rotate" src="https://dncache-mauganscorp.netdna-ssl.com/thumbseg/1619/1619140-bigthumbnail.jpg" />
  <br/>
  <img class="rotate" src="https://s-media-cache-ak0.pinimg.com/236x/35/98/76/359876a0f522051e747e878b9a6f551f.jpg" />
  <script>

      $(document).ready(function() {
        $("body").keydown(function(pressedkey) {
          console.log(pressedkey.key);
          if (pressedkey.key == "r" || pressedkey.key == "A") {
            //  alert("r was pressed");
            $("img").attr("src", "http://food.fnr.sndimg.com/content/dam/images/food/fullset/2010/8/30/5/FNM_Robert-Irvine-001_s3x4.jpg.rend.hgtvcom.966.1288.suffix/1371593293254.jpeg");
          }

          if (pressedkey.key == "Enter") {
            alert("Enter");
          }
        });
      });


  </script>
</body>

</html>