For our hello world, we'll be looking at how we can take in <input> and change text whenever that <input> is used.

We'll be looking at three different ways to update text:

  • vanilla JavaScript
  • jQuery
  • Vue

By using these three techniques, we'll see how Vue is an improvement and why we should use it.

Table of Contents

    Here's our HTML for this demo:

    <section id="app" class="section container">
        <h1 class="title">My Text Goes Here</h1>
    
        <input type="text" class="input">
    </section>

    Vanilla JavaScript

    Here's how we can listen to the input in vanilla JavaScript and update the h1 tag when typing occurs:

    const heading = document.querySelector('h1');
    const input   = document.querySelector('input');
    
    // listen to the input box for typing
    input.addEventListener('keyup', (e) => {
      const text       = e.target.value;
      heading.innerText = text;
    });

    jQuery

    Here's the code in jQuery. While it is very simple and a 1-liner, it can be hard to scale, especially when changing variable names or the target elements.

    $('input').on('keyup', (e) => $('h1').text(e.target.value));

    Vue

    Here's our full code in Vue. Vue makes the job of updating the text extremely organized and simple to reason about. This is one of the main benefits of Vue: organization and readable code.

    <section id="app" class="section container">
        <h1 class="title">
            Hi my name is {{ name }} and my message is: {{ message }}      
        </h1>
    
        <input type="text" class="input" v-model="name">
        <input type="text" class="input" v-model="message">
    </section>
    const app = new Vue({
        el: '#app',
        data: {
            name: 'Chris',
            message: 'hello world'
        }
    });

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.