Customize your JavaScript font with CSS

I am new to using JavaScript and I recently attempted to add a date to my website using the following code:

external script_

var mydate=new Date() 
var year=mydate.getYear() 
if (year < 1000) year+=1900 
var day=mydate.getDay() 
var month=mydate.getMonth() 
var daym=mydate.getDate() 
if (daym"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+ "")

The issue is that in my HTML file, it appears like this:

<p><strong>Current Date is : </strong><script src="js/datescript.js" id="sc"></script><br>

I want the text of the script to match the text of the <p>, how can I achieve this?

Answer №1

At first glance, it appears that some essential Javascript code is missing and the final if statement is quite incorrect as there are references to dayarray and montharray which have not been defined.

Furthermore, the JavaScript seems to only be assigning variables without actually displaying any output. When including the script inline, it will not dynamically insert output into the designated part of the DOM.

The best approach would likely be to assign an id to the element where you want the output to appear and then input the desired content accordingly.

Check out this Demo Fiddle for more clarity!

Here is how your HTML should look:

<p id='date'><strong>The Current Date is : </strong></p>

And this is the correct way to structure your Javascript:

var mydate = new Date();
var year = mydate.getYear();
if (year < 1000) year += 1900;

var day = mydate.getDay();
var month = mydate.getMonth();
var daym = mydate.getDate();

var el= document.getElementById('date');
el.innerHTML+=mydate;

Update:

If you prefer the output to also be bold, just adjust the placement of the id in your HTML like so:

Updated HTML Code:

<p><strong id='date'>Current Date is : </strong></p>

Answer №2

To display the current date in your HTML, follow these steps:

STEP 1:

Create an HTML element with a unique ID for the variable part of the date. For example:

<p><strong>Today's Date : <span id="dateVar"></span></strong>

STEP 2:

Have your JavaScript function execute when the document is ready (using jQuery is recommended):

$(document).ready(function() {
    showDate();
}

function showDate() {
    var currentDate = new Date();
    var year = currentDate.getYear();
    if (year < 1000) {
        year += 1900;
    } 
    var day = currentDate.getDay();
    var month = currentDate.getMonth();
    var date = currentDate.getDate();

    //Get dateString
    var element = document.getElementById('dateVar'); // Get the HTML element to insert the date
    element.innerHtml = *yourDateString*;
}

That's all you need to do to display the date on page load. If you want it to appear on a button click, call the showDate() function again after setting up an on-click event-listener (more information here).

Answer №3

Your JavaScript is responsible for generating HTML content, but the styling process remains the same as with any other HTML elements.

In this case, because the script element is situated within a paragraph, any text nodes it creates will inherit the same styling as other child nodes of that paragraph.

The issue arises when there are no other text nodes to compare with, as the remaining text in the paragraph is enclosed within a <strong> element.

To address this problem, consider moving the script inside the <strong> element to ensure consistent styling across all generated text.

Answer №4

Your external JS file contains multiple errors that need to be addressed before proceeding:

var mydate=new Date(); // Remember to always terminate statements with a semicolon!
var year=mydate.getYear();
if (year < 1000) 
    year+=1900;
var day=mydate.getDay();
var month=mydate.getMonth();
var daym=mydate.getDate();

if (daym"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+ "") 
  // The variables dayarray and montharray are not defined
  // Additionally, the if statement lacks a valid condition or block: if ( expression ) statement;

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

What could be causing Jquery to not function properly in an Angular controller?

Can someone please help me understand why my code is not working in JSFiddle? Any assistance would be appreciated! UPDATE: I have to admit, the negative feedback is disheartening. I may not know everything, but asking questions is how we learn. What' ...

Assign different classes to each element sequentially

Is there a way to display DIVs with the same class, initially hidden using CSS, one after another when a button is clicked? If you have any hints or directions on how to achieve this, it would be greatly appreciated. Thank you! $(".add_another").click ...

Issue with hamburger icon in Bootstrap navbar following height adjustment of the navbar

Although my navbar was functioning properly with the hamburger menu expanding down as expected, I encountered an issue after adjusting the height of the navbar. The hamburger button still worked and expanded the menu, but it only displayed the first item o ...

Dynamic path variables showcased in a static JSON configuration file

There is a JSON configuration for a backend CLI utility: { "searchRoots": ["$HOME"], "list": [] } If this was done with JavaScript, it would be: module.exports = { searchRoots": [process.env.HOME], list: [] }; The issue with using JSON instea ...

Encountering the error message "ws02 script tag does not define Map"

When I try to create a map using the following code: let myMap = new Map(); I encounter the error shown below. Script Error: The script engine encountered an error while executing the inlined Javascript function 'mediate'. com.sun.phobos.script. ...

Leverage NextJS's getServerSideProps feature with a specific sub path in the URL

For the past year, we have been implementing the solution detailed in NextJS deploy to a specific URL path (and Deploy your NextJS Application on a different base path (i.e. not root)) in our project. Our next.js server is hosted on another website under a ...

JavaScript Date() constructor failing to capture the correct day

Currently, I am in the process of developing an API that allows users to request transactions based on a specific year and month. This is how the API is structured: routes.get('/transactions/:member_id/:year/:month', (req, res) => { let { ...

Code for jQuery function

How do I update textareas with values after submitting a form? Below is the HTML code: <form id="productionForm" name="productionForm" method="POST"> <input type="text" id='ime_2'/> <textarea id='text_2'>& ...

Switching from an alert to a modal in React Native

I have a scenario where I want to transform an alert into a modal, which I have provided below. Can anyone guide me on how to achieve this? I am new to JavaScript, so the process is not clear to me at the moment. Any help would be greatly appreciated. Her ...

How can I incorporate the mix-blend-mode into my d3 stroke technique?

I am working with a packed circles graph that has circles with a black stroke on hover. I am interested in using the CSS property mix-blend-mode: multiply to change the circle border when hovered over. My goal is to have the stroke color be a darker shade ...

What is the process for displaying a JSON element within an HTML component in a Bootstrap modal?

My application is developed using CodeIgniter, and now I am looking to manipulate data using AJAX in jQuery. How can I display JSON elements within an HTML element in a Bootstrap modal? Here is the HTML and jQuery code: <td class="center"> < ...

Everything remained the same until an unexpected Ionic TypeError occurred, indicating that co.event is undefined

This problem has left me completely perplexed, as it's unlike anything I've experienced before. I'm currently developing an app in Ionic 2. Everything was running smoothly last night, but this morning I encountered a strange issue. While th ...

Tips for aligning text to match the starting point of other text

Currently, the text appears as follows: Lorem ipsum dolor sit amet consectetur adipiscing elit vitae orci elementum dictum I want it to look like this: Lorem ipsum dolor sit amet consectetur adipiscing elit vitae orci elementum dictum I ...

Is it possible to delay the execution of a JavaScript export statement in any way?

My current project involves developing a tool using React and Redux. To fetch data from the server, I am utilizing whatwg-fetch. The reducer in my code is responsible for creating its store within a callback function after the data has been successfully fe ...

What is causing Microsoft Edge to highlight this span and behave as though it's a hyperlink?

I am currently in the process of redesigning a website, and I've encountered an issue with the header markup. While the design looks fine on most browsers, it behaves strangely in Microsoft Edge on Windows 10. The phone number in the header is inexpli ...

Tips for refreshing the current Angular 2 Component

I'm looking for a way to refresh the same component in Angular 2. Can anyone provide guidance? Below is the code snippet I have: import { Component, OnInit, ElementRef, Renderer } from '@angular/core'; import { Router, ActivatedRoute, Para ...

What is the best way to determine if a URL parameter is present when compared to an Array?

Given the following two example URLs and code snippets, how can I utilize an Array as a reference to verify if the values are present in the UTM parameter? (Note: There will only be one UTM parameter at a time). example.com?utm=test example.com?utm=test ...

retrieve the parent id of <ul> elements and store them in an array

Here is the html code I am working with : <form> <ol> <li id="1" name="grandparent">Grand Parent <ol> <li id="2" name="parent">Parent <ol> <li id="3" name="child">Child < ...

Looking to access HTML elements in React without relying on setTimeout?

When developing a component that requires grabbing DOM elements to calculate heights, I initially resorted to using a setTimeout function to ensure the elements are captured once the page loads. While this solution worked perfectly, I am aware that there ...

Even in the face of errors, Selenium with Node.js continues to run seamlessly. The challenge arises specifically with the 107.xx version of the Chrome browser and Chrome driver

Currently, I am employed in a project involving NODE JS (javascript) with selenium webdriver. Package.json- “chai”: “^4.3.6”, “chromedriver”: “^107.0.3”, “geckodriver”: “^3.2.0”, “mocha”: “^10.0.0”, “mochawesome”: “^7. ...