Replace text and numbers with images using Javascript

Just dipping my toes into the world of JavaScript and working on a fun little project - a binary clock (yes, I know, super geeky)

I've managed to write most of the code, but now I want to take it to the next level. Currently, the numbers are being displayed as strings of 0s and 1s, but I'd really like them to show as images instead: 0.png and 1.png, which are saved in the same directory...

Here's what I have so far. Ideally, I'd love for these changes to happen within the same function...

function binClock ()
{
    var currentTime = new Date();

    var currentYear = currentTime.getFullYear();
    var currentMonth = currentTime.getMonth() + 1;
    var currentDate = currentTime.getDate();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    currentYear = currentYear.toString(2);
    currentMonth = currentMonth.toString(2);
    currentDate = currentDate.toString(2);
    currentHours = currentHours.toString(2);
    currentMinutes = currentMinutes.toString(2);
    currentSeconds = currentSeconds.toString(2);

    document.getElementById("year").firstChild.nodeValue = currentYear;
    document.getElementById("month").firstChild.nodeValue = currentMonth;
    document.getElementById("date").firstChild.nodeValue = currentDate;
    document.getElementById("hour").firstChild.nodeValue = currentHours;
    document.getElementById("min").firstChild.nodeValue = currentMinutes;
    document.getElementById("second").firstChild.nodeValue = currentSeconds;
}

To implement this on the webpage, I am calling the function on body load:

onload="binClock(); setInterval('binClock()', 1000)"

Answer №1

If you have an image element in your document with the ID your_img, you can update its source like this:

var path_to_img = ...
var image = document.getElementById('your_img');
image.setAttribute('src', path_to_img);

The variable path_to_img should be set to either the URL of 0.png or 1.png depending on a certain condition.

If there is no existing IMG element, you can create one and append it to the DOM using the following code:

var path_to_img = ...;
var parent_element_id = ...;
var parent = document.getElementById(parent_element_id);
var image = document.createElement('IMG');
image.setAttribute('src', path_to_img);
parent.appendChild(image);

In this case, parent_element_id refers to the ID of the element under which you want to insert the new IMG element.

Answer №2

Here is a demonstration of how it can be achieved using jQuery. However, if you prefer, you can easily replace it with the vanilla JavaScript DOM method.

const binaryYear = new Date().getFullYear().toString(2);
[...binaryYear].forEach(digit => {
    $('#year').append('<img src="../img/digit' + digit + '.png');
});

// Check out this modified demo link http://jsfiddle.net/user123/aBcDeF/2/

Answer №3

I have found my own way to solve this problem, understanding the syntax and the actions I am taking as I learn.

var currentYear = currentTime.getFullYear();
var currentMonth = currentTime.getMonth() + 1;
var currentDate = currentTime.getDate();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();

currentYear = currentYear.toString(2);
currentMonth = currentMonth.toString(2);
currentDate = currentDate.toString(2);
currentHours = currentHours.toString(2);
currentMinutes = currentMinutes.toString(2);
currentSeconds = currentSeconds.toString(2);

// Replacing numbers with image tags
currentYear = currentYear.replace(/0/g, "<img src='0.png' />");
currentYear = currentYear.replace(/1/g, '<img src="1.png" />');

currentMonth = currentMonth.replace(/0/g, "<img src='0.png' />");
currentMonth = currentMonth.replace(/1/g, '<img src="1.png" />');

currentDate = currentDate.replace(/0/g, "<img src='0.png' />");
currentDate = currentDate.replace(/1/g, '<img src="1.png" />');

currentHours = currentHours.replace(/0/g, "<img src='0.png' />");
currentHours = currentHours.replace(/1/g, '<img src="1.png" />');

currentMinutes = currentMinutes.replace(/0/g, "<img src='0.png' />");
currentMinutes = currentMinutes.replace(/1/g, '<img src="1.png" />');

currentSeconds = currentSeconds.replace(/0/g, "<img src='0.png' />");
currentSeconds = currentSeconds.replace(/1/g, '<img src="1.png" />');

// Updating HTML elements with the new values
document.getElementById("year").innerHTML = currentYear;
document.getElementById("month").innerHTML = currentMonth;
document.getElementById("date").innerHTML = currentDate;
document.getElementById("hour").innerHTML = currentHours;
document.getElementById("min").innerHTML = currentMinutes;
document.getElementById("second").innerHTML = currentSeconds;

You can see the code in action at

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

Working with Unicode characters in Java using String.toCharArray()

Is it possible to store Unicode characters in a char variable? For example, can I do something like char c = '\u1023'? String s = "ABCDEFG\u1023"; char[] c = s.toCharArray(); I want to convert the string 's' into a CharArray ...

JavaScript generating HTML code causing malfunctions

I have been attempting to implement the IN Place Editing feature using JQuery. Below is the code snippet editinplace.js $(document).ready(function() { //When div.edit me is clicked, run this function $("div.editme").click(function() { // ...

Encountered an error in NodeJs with mongoDB: TypeError stating that property 'fullname' is not defined

I am having issues storing user-entered data from an HTML form into MongoDB. The error message I receive is "TypeError: cannot read property 'fullname' of undefined" TypeError: Cannot read property 'fullname' of undefined at C:&bso ...

Tips for accessing a symbolic link in a Node.js application

I am looking to retrieve information about a symbolic link itself, rather than the contents of the file it is linked to. How can I achieve this in Node.js in a way that works across different operating systems? Detecting symbolic links using lstat is stra ...

`Issue with writing to file in Node.js`

A file is being cropped and loaded on the Angular side. I am grateful for this resource that has facilitated this process. SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xmy9 ...

jQuery live function is not functioning as anticipated

I am facing issues with ajax requests and simple <input type="submit"/>. I have a practice of loading views within other views, in a modular way, using jQuery's .load(url) function to move from one view to another. The problem arises when I loa ...

Code has been loaded successfully for react-loadable Chunks, however it has not been

Encountering a problem while trying to implement chunks in my React app using react-loadable Everything functions perfectly on webpack-dev-server in development mode. However, when I build the project and deploy it to the server, async components are ...

Creating HTML code from a website by utilizing XML

As someone who is not a developer and doesn't have much knowledge about java, I am seeking advice on potential solutions to achieve the following. This web hosting service enables users to retrieve data from their XML spreadsheets and embed them anyw ...

Accessing a specific value based on a selected option in Angular 2+

Examining the Angular 2+ code snippet below, there is an Array defined in TypeScript: models = [{idModele: 1, model: "Bianca", price: 500}, {idModele: 2, model: "etc", price: 600} ] The query here is about setting up a mechanism where selecting a specifi ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Whenever I refresh the page, the values remain the same and only update when I log in

Is it possible for the user's statistics to automatically update when they reload the page, based on the database? For example, if a user registers with Money-0, Diamond-0, Ruby-0 and then adds 10 money, can their stats be automatically updated to Mon ...

Having trouble integrating a custom plugin with CKEditor?

I am currently using version 4.7 of CKEditor, which is the latest version available. I am facing an issue where I cannot see a new custom plugin that I have added to the toolbar. I have checked my basic example of abbreviation (abbr) plugin but couldn&apos ...

Assistance with AJAX Reload Interval (Polling) Functionality

My project involves extracting small portions of text from multiple files (often just single words) and then applying a stylized script to them. Currently, everything is functioning correctly in terms of loading and displaying the text. However, since the ...

Generating PDF files utilizing AJAX technology with FPDF

I have a PHP script that generates a PDF file using the FPDF library. When I run the script directly, it successfully creates and opens the PDF in the browser. However, when I try to trigger this generation process through a button click using AJAX, it doe ...

Issue with updating a React form by re-rendering with a state variable

const [ usernameBox , setUsernameBox ] = useState(false); return( { usernameBox ? <> <div style={{ fontSize:"25px" }}>{"Sign up with Security"}</div> <TileI ...

JavaScript and jQuery validation issues persisting

Here is the HTML code I am using: <script src="js/validate.js"></script> <label>FIRST NAME:</label> <td> <input type="text" class="firstname" id="firstname" onKeyUp="firstname()" /> </td> <td> <label id=" ...

Implementing a django like feature using ajax requests

I am currently working on a template where I have a link for my article: <div id="voteUp"> <h4><a href="{% url "vote_up" article.id %}">Like {{article.up_vote}}</a></h4> </div> My goal is to increase the vote count for ...

"Enhancing HTML with jQuery Autocomplete for Advanced Search Results

I am in need of an autocomplete text box for my search feature, and I have decided to implement it using jQuery UI. Utilizing an ASP.NET Core API, I will retrieve search results in JSON format. These search results must be grouped with Bootstrap collapse ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...