What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing.

I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv/ (where you can see the effect when typing in the field), but instead of using the provided CSS, I'm trying to achieve the same result using compiled CSS. However, the uploader has not included a CSS alternative for the JavaScript code which is written in SCSS, so I'm unsure how to proceed.

Below is my code. Dreamweaver is also flagging that there is a missing "use strict" statement in my JavaScript code and that 'target' is undefined. I believe my HTML and CSS are correct, but any feedback would be appreciated.


$('.form').find('input, textarea').on('keyup blur focus', function(e) {

 var $this = $(this),
    label = $this.prev('label');

  if (e.type === 'keyup') {
    if ($this.val() === '') {
      label.removeClass('active highlight');
    } else {
      label.addClass('active highlight');
    }
  } else if (e.type === 'blur') {
    if ($this.val() === '') {
      label.removeClass('active highlight');
    } else {
      label.removeClass('highlight');
    }
  } else if (e.type === 'focus') {

    if ($this.val() === '') {
      label.removeClass('highlight');
    } else if ($this.val() !== '') {
      label.addClass('highlight');
    }
  }

});

$('.tab a').on('click', function(e) {

 e.preventDefault(); 

  $(this).parent().addClass('active');
  $(this).parent().siblings().removeClass('active');

 target = $(this).attr('href');

  $('.tab-content > div').not(target).hide();

  $(target).fadeIn(600);

});
  
/* CSS code snippet */
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="login.css"/>
<script type="text/javascript" script src="login.js"></script>

</head>

<body>


<div class="form">
      
      <ul class="tab-group">
        <li class="tab active"><a href="#signup">Your Personal Orlangutan</a></li>
      </ul>
      
      <div class="tab-content">
        <div id="signup">   
          <h1>Sign Up for Free</h1>
          
          <form action="/" method="post">
          
          <div class="top-row">
            <div class="field-wrap">
              <label>
                First Name<span class="req">*</span>
              </label>
              <input type="text" required autocomplete="off" />
            </div>
        
            <div class="field-wrap">
              <label>
                Last Name<span class="req">*</span>
              </label>
              <input type="text" required autocomplete="off"/>
            </div>
          </div>

          <div class="field-wrap">
            <label>
              Email Address<span class="req">*</span>
            </label>
            <input type="email" required autocomplete="off"/>
          </div>
          
          <div class="field-wrap">
            <label>
              Set A Password<span class="req">*</span>
            </label>
            <input type="password" required autocomplete="off"/>
          </div>
          
          <button type="submit" class="button button-block">Get Started</button>
          
          </form>

        </div>
        
        <div id="login">   
          <h1>Welcome Back!</h1>
          
          <form action="/" method="post">
          
            <div class="field-wrap">
            <label>
              Email Address<span class="req">*</span>
            </label>
            <input type="email" required autocomplete="off"/>
          </div>
          
          <div class="field-wrap">
            <label>
              Password<span class="req">*</span>
            </label>
            <input type="password" required autocomplete="off"/>
          </div>
          
          <p class="forgot"><a href="#">Forgot Password?</a></p>
          
          <button class="button button-block">Log In</button>
          
          </form>

        </div>
        
      </div><!-- tab-content -->
      
</div> <!-- /form -->

</body>
</html>

Answer №1

To ensure proper functionality, make sure to include the jquery reference either as a CDN or locally.

// Using CDN
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

// If using local file, place it in the same folder as the HTML page
<script src="jquery-2.2.3.min.js"></script>

Remember to execute the code after the DOM is ready.

You can insert the script after the last DIV and just before the </body> tag

Alternatively,

You can put the entire script in a separate file and wrap it within a function

  function startup() {
     // add your code here
  }     

Include this script with

<script type="text/javascript" script src="myscript.js"></script>

Then, call the function directly after the last div like so

<script>
    startup();
</script>

or on DOM ready

<script>
   $(function(){
     startup();
   }
</script>

A JSFiddle demo is available at this link

Answer №2

Prior to loading your login.js file, make sure to include jQuery.

You have the option of using a CDN for this purpose:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Alternatively, you can download jQuery and include it locally in your project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for submitting an e-mail through an HTML form with the help of Node.js and Gulp

Today, I've been tackling the challenge of creating an HTML contact form that can send an email using Node.js and Gulp. However, I'm struggling to find a solution. Using a relative path to a simple .PHP file doesn't seem to be working, so it ...

Utilizing RequireJS with Laravel 4

I am trying to use require js and laravel to manage the assets directory. I have placed the require.js file in the assets/js directory, along with main.js. The main.js file contains: require.config({ baseURL: '', paths: { userPre ...

What is the best way to enable a disabled MUI MenuItem within a table that is being mapped, based on a specific item in the

In my table, I have a mapped object of users: {users.map((user,index) => { <TableRow key={index}> ... The final cell in the table contains a button that is linked to an MUI Menu. One of the menu items should be disabled if a specific aspect of ...

Final div class nested within the HTML and styled with CSS

Is there a way to keep the last div (class) from sliding underneath? I applied margin-right to .artist_wrap. I assumed that using overflow: hidden would contain it within #music_videos_wrap, but it just disappears. Any assistance is greatly appreciated. H ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

Guide to switch background image using querySelector

I am currently trying to figure out how to set the background image of a div block by using querySelector. I have attempted various methods in my test code below, but unfortunately none seem to be working. Can someone please provide assistance? <!DOC ...

Selenium WebDriver: The challenge of using visibilityOfElementLocated when the element is not actually visible

I've encountered an issue with the Firefox Webdriver where it fails to accurately determine if an element is visible. Here is the code I am using, which incorrectly indicates that the element is visible: wait.ignoring(UnhandledAlertException.class).u ...

The JavaScript function I created to remove the last item in an array is not functioning correctly when it encounters an "else

My button has been designed to delete the last index from this.fullformula, which is a string. However, I've encountered an issue with deleting characters from this.result, which is an integer. Instead of looping over the function, it only deletes one ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

Using scriptlet based IDs in jQuery selectors involves incorporating JavaScript syntax within the jQuery selector to

I need to incorporate dynamic ids in my form, which are based on jsp variables within a scriptlet. How do I correctly select the desired element using jQuery's id selector without encountering any errors? Below is the code snippet: <form name="in ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

What is the best way to clear an XML or table?

As I delve into learning Javascript, I've been experimenting with different approaches to achieve a specific functionality. I'm trying to implement a button that can toggle or hide XML data in a table. My attempts so far have involved adding anot ...

Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code: [ { "id": 364, "siteName": "FX21 - PortA", }, { "id": 364, "siteName": "FX21 - PortB", }, { "id": 370, "siteName": "FX05 - ER", }, I'm tr ...

Vue.js known as javascript hooks

I've been working on connecting Vue.js with velocity.js. Following a guide, I found an example that doesn't use a named transition. Currently, my transition code looks like this: <transition name="collapse"> https://v2.vuejs.org/ ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

Is there a Node template engine similar to EJS that seamlessly integrates with HTML templates?

Is there a template engine for NodeJS similar to EJS that doesn't alter the original HTML template structure with its use of parentheses? In EJS, one might utilize the following code snippet to embed specific data into the HTML template: <script& ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

Step-by-step guide to creating a border around text with a number included in between the lines

Is there a way to replicate the appearance of the image shown below using CSS, Bootstrap, or other client-side methods? ...

IE11 experiencing issues with font loading

I need help troubleshooting why the fonts are not loading properly in the body section of my articles, specifically when viewed in Internet Explorer. Take a look at an example article here: I am fetching from this CSS file: , and I have included the nece ...