Javascript; Review and the Fundamentals

Before going over this section, if you need a refresher on the very basics of javascript about DOM and BOM elements, please refer to this javascript simulator.

Mouse Interaction
onclick and ondblclick Event:

The most straight forward and simple mouse interaction with a web browser is "clicking". You can use a click of the mouse as a trigger for an event to happen: to name a few - changing the image, changing the text, changing a css style of a section, etc. We already know an html tag that uses the click of a mouse to do an action: <a> tag. The action of clicking on a section of html surrounded by the <a> tag can open a new html page. Like so, we can use the click on a section of our html to trigger a set of actions that we can define in javascript.

 <div onclick="clickFunction()" id="click-section"></div>
                

In the above example, the <div> of id "click-section" is now waiting for a click event, and ON CLICK of the <div>, it will trigger the clickFunction() function. Looking at the way this is written in html, onclick="clickFunction()" is written INSIDE of the OPENING TAG of the html element. This is because onclick event (and all other events for this matter) is an attribute that belongs to this particular html tag. This means that this onclick event that calls clickFunction() when triggered is attached specifically to this <div> ONLY. Clicking on other html elements of the web page will NOT trigger the clickFunction() function. But this means you can attach onclick events to many html elements of the web page, and have them call other functions.

 <div onclick="clickOne()" id="section-one"></div>
 <div onclick="clickTwo()" id="section-two"></div>
                

In the code above, clicking on the <div> with id "section-one" will run the clickOne() function, and clicking on the <div> with id "section-two" will run the clickTwo() function.

You can also make a distinction between a single click and a double click. A single click can be detected using the onclick event, like we saw above, and a double click can be detected using the ondblclick (on-double-click but without the vowels in the word "double") event.

onmouseover and onmouseout Event:

The mouse doesn't have to click on an html element to trigger a javascript function. The mouse cursor can also simply be OVER or OUT of an html element. These actions can be detected using onmouseover and onmouseout events.

Let's see the mouse events that we've looked at so far in action:



                

function clickEvent(){
    document.getElementById('click-div').style.backgroundColor = "red";
}

function dblclickEvent(){
    document.getElementById('click-div').style.backgroundColor = "blue";
}

function onmouseoverEvent(){
    document.getElementById('click-div').style.border = "solid 5px green";
}

function onmouseoutEvent(){
    document.getElementById('click-div').style.border = "dotted 10px yellow";
}
                
onmousemove Event:

You can also trigger a javascript function whenever the mouse cursor is moving using the onmousemove event. Note that this event usually gets attached to the <body> tag of the html document, because if attached to a particular html element, it will only be triggered when the mouse is moving WITHIN the html element. See that the below text changes to reflect the x and y position of the mouse as it moves.

One thing that you can do with this event is to use the position of the mouse to change the position of an html element. Additionally, by adding a function to an onclick event to allow the html element to move, you can fake a drag-and-drop effect. Click on the red square below to move it around and click it again to leave it where it is.

Click to view it as a full web page.


With the things that we've learned about mouse events, take a look at the demo below. Clicking on the images will change the source of the image and the mouse position changes the innerHTML and backgroundColor of the centered text.

Click here to download the sample images used below to following with the demo - but of course, you can use your own images.

Click to view it as a full web page.

CSS:

html, body{
    margin: 0;
    overflow: hidden;
    height: 100%;
    font-family: 'Helvetica', sans-serif;
}

#left-section, #right-section{
    width: 50%;
    height: 100%;
    float: left;
}

#left-section:hover, #right-section:hover{
    cursor: pointer;
}

#left-img, #right-img{
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
}

#text-section{
    position: absolute;
    top: calc(50% - 32px);
    width: 100%;
    text-align: center;
}

#title-text{
    background-color: black;
    color: white;
    font-size: 64px;
}
                

HTML:

<body onmousemove="changeText()">
    <div id="text-section">
        <span id="title-text">Blue or Orange?</span>
    </div>
    <div onclick="changeBlue()" id="left-section">
        <img id="left-img" src="img/basicJs/blue1.jpg">
    </div>
    <div onclick="changeOrange()" id="right-section">
        <img id="right-img" src="img/basicJs/orange1.jpg">
    </div>
</body>
                

Javascript:

var bIndex = 1;
var oIndex = 1;

var leftText = "Blue?";
var rightText = "Orange?";
var centerText = "Blue or Orange?"

function changeBlue(){
    if(bIndex < 4){
        bIndex++;
    }else{
        bIndex = 1;
    }

    document.getElementById('left-img').src = "img/basicJs/blue" + bIndex + ".jpg";

}

function changeOrange(){
    if(oIndex < 4){
        oIndex++;
    }else{
        oIndex = 1;
    }

    document.getElementById('right-img').src = "img/basicJs/orange" + oIndex + ".jpg";

}

function changeText(){
    var x = event.clientX;
    var y = event.clientY;

    var w = window.innerWidth;
    var titleSpan = document.getElementById('title-text');

    if(x < w / 3){
        titleSpan.innerHTML = leftText;
        titleSpan.style.backgroundColor = 'blue';
    }else if(x >= w / 3 && x < w * 2 / 3){
        titleSpan.innerHTML = centerText;
        titleSpan.style.backgroundColor = 'black';
    }else{
        titleSpan.innerHTML = rightText;
        titleSpan.style.backgroundColor = 'orange';
    }

    // console.log(x + ", " + y);
}
                
Scroll Interaction

You can also use the scrolling position of your web page to trigger a javascript function. Same as the way it is for click events that we looked at in the above section, there is an event that will wait for scrolling to happen, which you can attach a javascript function to do a set of actions according to the scrolled position (amount of pixels scrolled).

<body onscroll="scrollFunction()"><body>
                

One thing to note, that is different from the way we attach a click event to an html element, is that you would normally attach the onscroll event for the whole body, rather than a particular section of your html document. This is because you need a "scrollable area". If there is nothing to scroll in the area of the html element that you have attached the onscroll event to, then obviously, it won't do anything. However, if you DO have a section of an html element that can scroll, you can of course attach the onscroll event there. Inside of the scrollFunction(), you can get the how much the html element that the event is attached to (in this case - the whole body) by using event.scrollX and event.scrollY

If your web page scrolls horizontally, you would use the event.scrollX value to check how much it has been scrolled in the x direction and if your web page scrolls vertically, you would use the event.scrollY value.

function scrollFunction(){
  var xpos = event.scrollX;
  var ypos = event.scrollY;
}
                

In the example above, every time your web page (more accurately, the body of your web page) has been scrolled, it will save the values (in pixels) in variables called xpos and ypos. You can use these to variables with if-statements, to do another set of actions accordingly.

function scrollFunction(){
  var xpos = event.scrollX;
  var ypos = event.scrollY;

  if(ypos < 500){
    document.body.style.backgroundColor = "red";
  }else{
    document.body.style.backgroundColor = "blue";
  }
}
                

In the above code, IF the value of the ypos variable is less than 500 (meaning the webpage has been scrolled down less than 500px), then the backgroundColor of <body> is set to red. ELSE (meaning the webpage has been scrolled down more than 500px), the backgroundColor is set to blue.

But, what if you want to base your if-statements based on the total width or height of the html element? All html elements have a property called scrollWidth and scrollHeight that you can use in javascript. scrollWidth will return the amount of width available to scroll, and scrollHeight returns the amount of height available to scroll. Thus, for our example, document.body.scrollHeight will return the total height the body has available for the user to scroll.

function scrollFunction(){
  var xpos = event.scrollX;
  var ypos = event.scrollY;
  var bodyHeight = document.body.scrollHeight;

  if(ypos < bodyHeight / 2){
    document.body.style.backgroundColor = "red";
  }else{
    document.body.style.backgroundColor = "blue";
  }
}
                

By using the scrollHeight value, now we can create conditions based on the scrollable height of our body, without knowing the exact height of the body beforehand.

With the things we've learned about using the onscroll event, take a look at the below demo.

Click here to download the sample images used below to following with the demo - but of course, you can use your own images.

Click to view it as a full web page.

CSS:

html, body{
    margin: 0;
    overflow-x: hidden;
    font-family: 'Helvetica', sans-serif;
}

.section{
    width: 100%;
    height: 100%;
}

.section-img{
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
}

#float-section, #title-section{
    position: fixed;
}

#float-section{
    top: 0;
}

#title-section{
    top: calc(50% - 24px);
    width: 100%;
    text-align: center;
}

#float-text{
    background-color: black;
    color: white;
    font-size: 18px;
}

#title{
    font-size: 48px;
    background-color: white;
}
                

HTML:

<body onscroll="changeStory()">
    <div id="float-section">
        <span id="float-text"></span>
    </div>
    <div id="title-section">
        <span id="title"></span>
    </div>
    <div class="section">
        <img class="section-img" src="img/basicJs/land1.jpg">
    </div>
    <div class="section">
        <img class="section-img" src="img/basicJs/land2.jpg">
    </div>
    <div class="section">
        <img class="section-img" src="img/basicJs/land3.jpg">
    </div>
    <div class="section">
        <img class="section-img" src="img/basicJs/land4.jpg">
    </div>
    <div class="section">
        <img class="section-img" src="img/basicJs/land5.jpg">
    </div>
</body>
                

Javascript:

var story1 = "This is a story.";
var story2 = "Your character is in danger.";
var story3 = "How will your character solve this?";
var story4 = "Miraculously your character solves the problem.";
var story5 = "Happily ever after."

function changeStory(){
    // console.log(window.scrollY);

    var ypos = window.scrollY;
    var h = document.body.scrollHeight;
    var titleSpan = document.getElementById('title');

    document.getElementById('float-text').innerHTML = window.scrollY + "px scrolled";


    if(ypos < h / 5){
        titleSpan.innerHTML = story1;
    }else if(ypos >= h / 5 && ypos < h * 2 / 5){
        titleSpan.innerHTML = story2;
    }else if(ypos >= h * 2 / 5 && ypos < h * 3 / 5){
        titleSpan.innerHTML = story3;
    }else if(ypos >= h * 3 / 5 && ypos < h * 4 / 5){
        titleSpan.innerHTML = story4;
    }else{
        titleSpan.innerHTML = story5;
    }

}