Code functioning flawlessly on JSFiddle, but encountering errors on Chrome and IE

I recently implemented some JavaScript code to add a sliding animation effect to the login form that appears with an accompanying picture.

After testing the code on JS Fiddle, everything worked perfectly. However, upon copying and pasting the same code into Chrome or Internet Explorer, nothing seems to be happening.

Both browsers have JavaScript enabled, so I'm not sure why it's not functioning correctly.

Below is the HTML snippet:

<body>
<header>
    <div class="Header">
        <nav id="navi">
            <img src="http://www.bilder-upload.eu/upload/79a9ee-1471738072.png" class="logo"/>
            <img src="C:\Users\Hasaan\Desktop\HasaanNEW\Hasaan\Media\Images\menu-icon.png" class="menu-icon"/>

            <ul>        
            <li> <a class="navlinks" href="#">Home</a> </li>
            <li> <a class="navlinks" href="#">About us</a> </li>
            <li> <a class="navlinks" href="#">Our Services</a> </li>
            <li class="last" id="login"> <a href="#">Login</a>
                <div class="dummy">
                <ul>
                <li  class="loginform"> <form method="post" action="">
                  <p><input type="text" name="login" value="" placeholder="Username or Email"></p>
                  <p><input type="password" name="password" value="" placeholder="Password"></p>
                  <p class="remember_me">
                     <label>
                      <label>
                   <input type="checkbox" name="remember_me" id="remember_me">
                           Remember me on this computer
                      </label>
                      </label>
                     </p>
                      <p class="submit"><input type="submit" name="commit" value="Login"></p>
                    </form>
                    </li>
                </ul>
                </div>
            </li>


            </ul>           
            </li>

        </nav>  
    </div>
</header>
</body>
</html>

CSS:

@import 'https://fonts.googleapis.com/css?family=Montserrat';
@import 'https://fonts.googleapis.com/css?family=Roboto+Slab';

body {
    margin: 0;
    background: #808080 ;
    font-family: "Montserrat", Helvetica, Arial, sans-serif;
    color: #fff; 
}

.show {
    display: none;
}
...
... (Remaining CSS code)
...

And finally, the JavaScript function:

$(".last").on('click', function() {
  $('li div ul').toggle('');
});
$('.nav > li div ul li a').click(function(e) {
  e.stopPropagation();
});

For better understanding and testing, please refer to the following link of the working version in JS Fiddle:

https://jsfiddle.net/5vs30x6f/

Answer №1

Don't forget about this

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

$(".last").on('click', function() {
  $('li div ul').toggle('');
});
$('.nav > li div ul li a').click(function(e) {
  e.stopPropagation();
});
@import 'https://fonts.googleapis.com/css?family=Montserrat';
@import 'https://fonts.googleapis.com/css?family=Roboto+Slab';

body {
    margin: 0;
    background: #808080 ;
    font-family: "Montserrat", Helvetica, Arial, sans-serif;
    color: #fff; 
}

.show {
    display: none;
}
...
... (CSS code omitted for brevity)
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="Header">
        <nav id="navi">
            <img src="http://www.bilder-upload.eu/upload/79a9ee-1471738072.png" class="logo"/>
            <img src="C:\Users\Hasaan\Desktop\HasaanNEW\Hasaan\Media\Images\menu-icon.png" class="menu-icon"/>

            <ul>        
            <li> <a class="navlinks" href="#">Home</a> </li>
            <li> <a class="navlinks" href="#">About us</a> </li>
            <li> <a class="navlinks" href="#">Our Services</a> </li>
            <li class="last" id="login"> <a href="#">Login</a>
                <div class="dummy">
                <ul>
                <li  class="loginform"> <form method="post" action="">
                  <p><input type="text" name="login" value="" placeholder="Username or Email"></p>
                  <p><input type="password" name="password" value="" placeholder="Password"></p>
                  <p class="remember_me">
                     <label>
                      <label>
                   <input type="checkbox" name="remember_me" id="remember_me">
                           Remember me on this computer
                      </label>
                      </label>
                     </p>
                      <p class="submit"><input type="submit" name="commit" value="Login"></p>
                    </form>
                    </li>
                </ul>
                </div>
            </li>


            </ul>           
            </li>

        </nav>  
    </div>
</header>

Answer №2

Ensure that your jQuery code is properly enclosed in

$( document ).ready(function() {
  // Your custom code should be placed here
});

For more information, you can refer to this link. Typically, the script should only run once the DOM structure has been fully assembled

Here's an example of how your code should look:

$( document ).ready(function() {
  $(".last").on('click', function() {
    $('li div ul').toggle('');
  });
  $('.nav > li div ul li a').click(function(e) {
    e.stopPropagation();
  });
});

Remember to include jQuery in the head section of your webpage

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

Answer №3

I have a feeling that you may have overlooked adding the window.onload listener, as this is the main distinction between running code on JSFiddle and using pure Javascript. When jQuery is loaded, JSFiddle automatically executes your code. You can rectify this by implementing something like the following:

window.addEventListener('load', function(){
    // Your code here
});

Alternatively, you could opt for using jQuery instead:

$(document).ready(function(){
    // Your code here
});

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

Determine if the content has finished loading once it has been added using JavaScript

I am currently working on a project in pure JavaScript that involves implementing a feature similar to Facebook's message loading. This means that when you scroll to the end of the page, new HTML content is loaded and added to the page. The additional ...

How can I stack two appbar components from Material Ui on top of each other without the vertical line separating them?

I am facing a challenge while trying to incorporate two AppBar components in Material-UI, stacked one on top of the other. The problem arises when a line appears at the end of the first AppBar, overlapping with the second one. Click here to view an image ...

Ensure portrait orientation images have a restricted width to maintain their aspect ratio

On a responsive site, I have set up flexslider to showcase both landscape and portrait orientation images. The smoothHeight: true option is enabled to adjust the height according to the images. However, at the largest media query where the flexslider cont ...

JSON does not send information to the specified web address

Attempting to send some data to the following URL: " $(function() { var frm = $(document.myform); var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray()); ...

Troubleshooting: Issues with Custom Image Loader in Next.js Export

I'm encountering a problem while attempting to build and export my Next.JS project. The issue lies with Image Optimization error during the export process. To address this, I have developed a custom loader by creating a file /services/imageLoader.js ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...

Is there a way to emphasize a particular link in a navigation bar without causing changes to the other links?

I am trying to create a hover effect for my links where they raise up when hovered, but I don't want the other links in the navigation bar to be affected. However, whenever I hover over one link, the others move downward as well. Can anyone help me so ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

When Select2 doesn't find a suitable option, the text "other" will be displayed

Is it possible to show a default option in select2 dropdown if the user's typed input does not match any available options? $("something").select2({ formatNoMatches: function(term) { //return a predefined search choice } }); I have searched ...

Inform the user that an error has occurred when attempting to perform an invalid

While using redux promise middleware for my front end, I am wondering about the correct status code to throw from my backend in case of an error. I know that I can use res.status(500).json(something), but is 500 the appropriate code for all types of erro ...

Adding new elements to a div container

My goal is to populate a div element with items based on elements from an array. I need to duplicate an existing element on the page and append the new version to the div. Let me provide the code for better understanding: JavaScript: function apply(list ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...

What are the steps to develop a progress bar using PHP and JavaScript?

In the application I'm developing, PHP and JavaScript are being used extensively. One of my tasks involves deleting entries from the database, which is a time-consuming process. To keep the end-user informed, I would like to provide updates on the pr ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

The value of the innermost dropdown in the AngularJS Cascading dropdown is not being retrieved when it is selected

CSS <div ng-controller="DynamicCtrl"> <h1>Dynamic - Focused</h1> <p>This method works well when data is constantly changing</p> <div> Category: <select id="category" ng-model="items" ng-options="category ...

Error message: Invalid input for directive, only numeric values are accepted

I need help with a directive that restricts non-numeric symbols in an input field. Below is the code for the directive: import { NgControl } from "@angular/forms"; import { HostListener, Directive } from "@angular/core"; @Direct ...

reducing the size of the text field

Is there a way to adjust the height of the text box? So far, modifying the style sheet hasn't worked. Below is my code along with the corresponding style sheet. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css ...

Struggling with Bootstrap 4 Navigation - Placement of Icons Challenge

I'm struggling with aligning the search and shopping cart "icons" on mobile. On desktop, the icons should be positioned to the right of the menu as they currently are. However, I want to move the icons to the left side of the hamburger icon in respon ...

Both Fluid and Fixed layouts offer different advantages and disadvantages for website

Is there a way to position two divs side by side, where one div is 75% width and the other is 25% width? Additionally, can we place another div on top with margin:0 auto; to center the content of the page with a width of 986px? Here is an example code sni ...

There seems to be an issue with the React Hooks edit form where it is not selecting the record to edit. Although the currentId is correct

I have a simple CRUD React Hooks app with an ASP.NET Core Web API. The Courses component displays a list, but when I click on a link to edit a particular course, the form shows up with empty fields. Here is the JSX for the Courses component: import React, ...