Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle, where I have selected no-wrap <body>.

However, when I try the same code from my editor (Netbeans), it does not work. I have the JavaScript code in a separate file and the jQuery library added in the head.

Here is my jsFiddle

var addition = 1;
var now = new Date(); //set time
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var date = (day) + "." + (month) + "." + now.getFullYear();

function add() {
   var operationTitle = $("#title").val();
   var rowType = $("#type").val();
   var urgencyLevel = $("#urgency").val();
   

   $("#insertion").before("<tr id='new'><td>" + addition + "</td><td>" + operationTitle + "</td><td>"      + rowType + "</td><td>" + urgencyLevel + "</td><td>" + date + "</td></tr>");

     addition = addition + 1;
   };
    $("table").delegate("tr", "click", function () {
       $(this).addClass("highlight");
    });

    $("#remove").click(function () {
       $(".highlight").hide();
    });

Answer №1

...while using jsFiddle, I have opted for no-wrap.

You specifically selected No wrap - in <body>.

However, when trying the code from my editor (Netbeans), it does not work as intended. My JavaScript code is in a separate file and jQuery library has been added to the head section.

(emphasis mine)

The issue lies in placing them inside the body instead, just before the closing </body> tag.

If scripts are placed in the head, none of the DOM elements in the body exist at the time when the script runs since scripts run when encountered* and elements may not have been created yet. Moving the script to the end of the body ensures all elements exist by that point. This allows you to interact with them, attach event handlers, etc.

If there was a necessity to place the scripts in the head, you could utilize jQuery's ready function, which delays execution until the DOM is "ready." However, this is generally used in situations when control over the placement of the script tag is limited.


* "scripts are run when they're encountered" — unless async or defer attributes are used and supported by the browser.


Unless there are specific reasons to do otherwise, following the usual layout (recommended by YUI Best Practices and Google's Closure library engineers, among others) involves putting CSS in the head and scripts at the end of the body, such as:

<!doctype html>
<html>
<head>
<meta charset="UTF-8"><!-- Specify your desired charset -->
<title>Your title</title>
<!-- `link` and/or `style` tags for CSS -->
<!-- other content within `head` -->
</head>
<body>
<!-- main body content -->
<!-- include script tags here -->
</body>
</html>

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

Rails backend is struggling to receive Crossrider ajax post requests with JSON payload

I am encountering an issue where my attempts to post a JSON object to a remote server (Rails) are failing. The POST parameters seem to be converted to a url-encoded string instead of being sent as 'application/json'. Here is an example of what I ...

The functionality of arguments in the whenAllDone promise/deferred javascript helper seems to fail when attempting to encapsulate existing code within a Deferred

My goal is to implement the solution provided in TypeScript from Stack Overflow: UPDATE 2 - The issue with the original answer is that it does not support a single deferred. I have made modifications to reproduce the error in his fiddle. http://jsfiddle.n ...

What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that ...

Ways to apply autofocus to one element once another element already has it?

I have encountered an issue while attempting to give a textarea autofocus using the autofocus attribute. Upon doing so, I receive an error message in the console that says: Autofocus processing was blocked because a document already has a focused element. ...

Position the li elements within the ul at the bottom

I am trying to align a li element at the bottom of a ul list. +------+ | li1 | | li2 | | li3 | | | | | | | | li4 | +------+ Any suggestions on how to achieve this? MY ATTEMPTED SOLUTION: li4 { position: fixed; bottom: 0; } W ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Is there a way to have a div element with a box-shadow effect on top of its h1 child element?

I am facing an issue where a div with a box-shadow and an h1 inside are not aligned properly, causing the shadow to not cover the h1 element. Below is the code snippet in question: h1 { position: absolute; top: 50%; left: 44%; -webkit-t ...

The Ajax success callback is failing to update the background-image property after receiving a successful JSON response

I am struggling with setting a background image in wordpress despite receiving a successful ajax response. The image url is being returned successfully in the json response, but I can't seem to set it as a background image. Here is the ajax function ...

Passing dropdown value from Razor view using AJAX

I would like to pass the value of my dropdownlist @Html.DropDownListFor(model => model.selection, Model.liste_selection, new {@id="Selection", @class = "form-control" }) using this ajax post <script> $('#valider').on("click",fu ...

When the section comes into view on the screen, the CSS animation will play only one time

While browsing through , I found some fantastic animations that inspired me. The animations at the header seem to be standard CSS animations with delays. However, as you scroll down and other sections become visible, the animations reappear only once. Can ...

Converting Angular object into an array: A step-by-step guide

In Angular, I have retrieved an object that contains the following information: quiz.js:129 m {$promise: Promise, $resolved: false} 439: "https://mysite.no/sites/default/files/styles/quiz_large/public/fields/question-image/istock_000059790188_large.jpg ...

Can the CSS be used to conceal the PNG image while still preserving the drop shadow effect?

I recently applied the "Filter: drop-shadow" effect to my png photo and it worked perfectly. However, I am now interested in hiding the actual png image while retaining the shadow effect. My initial attempt involved adjusting the translate and drop-shadow ...

Activate the WebDAV feature within the .htaccess file

Can WebDAV be activated through an .htaccess file? I'm experiencing issues with Plesk not recognizing my modified config files that have WebDAV enabled. Is it feasible to enable WebDAV without using an .htaccess file? ...

Distorted image display on Bootstrap card in Internet Explorer

My layout includes bootstrap v4 cards, but I'm having issues with distorted images in Internet Explorer 11. It seems that IE is not recognizing the height: auto attribute from the img-fluid class. Should I set a custom height for the card images? Inte ...

Secure your API routes in NextJS by using Passport: req.user is not defined

Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed. After successfully implementing authentication on my website using passport and next-connect based on a ...

Customizing checkboxes in React with JSS: A step-by-step guide

I'm currently working on customizing CSS using JSS as my styling solution, which is proving to be a bit complex while following the w3schools tutorial. https://www.w3schools.com/howto/howto_css_custom_checkbox.asp HTML: <label class="container"& ...

Extract JSON data from a zipped file using adm-zip

Trying to extract and parse a JSON file named manifest.json from the root of a zip archive has been my current challenge. Regardless of the specific zip file being processed, the JSON file will always be named manifest.json. Presently, this function is w ...

Waiting for Angular's For loop to complete

Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them ...

Angular2 fire fails because the namespace 'firebase' does not export the member 'Promise'

I recently set up Angular 2 Fire on my project. "angularfire2": "^5.0.0-rc.0", Now, in my root module (app module), I have the following setup: export const firebaseConfig = { apiKey: "mykey", authDomain: "....", databaseURL: "...", projectId: ...