Use Javascript to display an image based on the date, otherwise hide the div

I'm looking to implement an image change on specific dates (not days of the week, but actual calendar dates like August 18th, August 25th, September 3rd, etc).

Here's the div I'm working with:

<div id="matchday">
    <img id="home" src="css/images/teams/home.png">
    <span class="verses">V</span>
    <img id="away" src="css/images/teams/away1.png">
</div>

My objective is to change the "away" image to away2.png, away3.png ... away20.png, etc., on specific match dates.

To add complexity, instead of having a default "away" image, I want the div to only be displayed on matchdays (the specified dates for image changes).

Answer №1

selectedDate represents a specific day within a month (1-31), while selectedMonth corresponds to a particular month (0-11):


if(getCurrentDate() == selectedDay && getCurrentMonth() == selectedMonth){
document.getElementById("image").src = "image834759837489734.png" //insert any imageN.png you desire
}

Answer №2

If you're working with Javascript, don't forget about the handy Date object that comes built-in. To get started, simply create a new Date object like this var date = new Date(). If you want a helpful tutorial on how to manipulate time and date values using Javascript's Date object, check out this link: , or consider using the Moment library available at http://momentjs.com/. You can then use the instantiated date object in an if / switch statement to display the desired content effectively.

Answer №3

   imgArray= new Array();
    for(index=1;index<=20;index++) {
        imgArray[index]=index+".png";  //Assign the name of your image files as 1.png,2.png etc.
    }

if(getDate()==desiredDay && getMonth()==desiredMonth){
    document.getElementById("away").src=imgArray[index];
}

Derived from nicael's response

Answer №4

For your CSS styling, make sure to include the following:

#gameTime {
   display: none,
   ...
}

To implement this using JavaScript and jQuery:

$(document).ready(function(){

   //Specify the date and time of the match
   var gameDateTime = new Date(year, month, day, hours, minutes, seconds, milliseconds);

   //Compare current date with the specified match date
   if($.now() == gameDateTime.getTime()) {

      //Display the div element for the match (adjust values accordingly)
      $("#gameTime").css("display", "block");
   }
});

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

Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string. Suppose I have two checkboxes labeled: label1 and label2, my a ...

Combining two JSON datasets using specific fields in Javascript

Two JSON inputs are provided: [ { userId: 32159, userFirstName: "john", userLastName: "doe", plans: [ ] }, { userId: 32157, userFirstName: "dave", userLastName: "mess", plans: [ ] } ] and [ { userId: ...

Is it possible to trigger the alert message by utilizing this code snippet?

Is it possible to display a message using this function? var start_database = function() { alert('hello'); }; window.setTimeout(start_database, 1000); ...

Form using Ajax technology, including two drop-down menus sourced externally

Is there a way to automatically populate a second drop-down list with all models once a selection is made in the first drop-down on a form? Below is the code snippet: <form> <div class="landing_quote_left"> ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

The jQuery slider's next button is not functioning as intended

jQuery('#slider-container').bjqs({ 'animation' : 'slide', 'width' : 1060, 'height' : 500, 'showControls' : false, 'centerMarkers' : false, animationDuration: 500, rotationS ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

The webpage is experiencing a glitch as the favicon fails to appear

I am having trouble showing a favicon on my website. I'm currently using IE8 as my browser. In my .aspx page, I have included the following markup: <head runat="server"> <link rel="shortcut icon" href="Images/favicon.ico" /> </head&g ...

Styling CSS to place an image in between text and background coloring

As I try to replicate a happy accident of mine, which originally occurred during my first attempt at CSS: I was just randomly adding selectors when I stumbled upon this unique layout. However, as I proceeded with rewriting the file, I failed to save the o ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

Having trouble inputting values into the Filter Value Datagrid component in Material-UI while using ReactJS

When using the Material-UI DataGrid, I'm facing an issue where I can't enter or edit any values in the filter field as shown in the image below. It appears that the filter value input is disabled. I would appreciate any assistance in resolving th ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

Changing the line spacing of label elements in HTML forms

I am encountering an issue with my form where the spacing between the two lines of the <label> element is too large and I am unable to adjust the line-height. For reference, I have applied the same CSS styles to a <label> and a <p>. Surp ...

Can anyone share tips on how to effectively center navbar link items with Bootstrap?

I recently tried to center the navigation links on my website using Bootstrap. I followed the instructions on the w3schools documentation and also watched a YouTube video for additional guidance. Both resources suggested adding the justify-content-center c ...

Why is my React Native button's onPress event not functioning correctly?

I am encountering an issue with the onPress event handler. I have tried multiple solutions but none seem to work with the handleClick function. Here are the different approaches I attempted: onPress={this.handleClick} onPress={this.handleClick()} onPress= ...

IE 7 textarea malfunctioning with word spacing issues

I have a website using the LAMP stack with a form that users fill out. Strangely, when I view the submitted form data in IE 7, it adds line breaks between each word. The form is simple with input elements and a text area. Submitting the form in FF3+, IE8, ...

What is the best way to transform the HTML retrieved from an AJAX GET request into an object using JQuery?

$.ajax({ method:"get", url:"/wall", data:"ajax=1", beforeSend:function(){}, success:function(html){ $("#grid_mason").append(html); //Inserting additional co ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Tips for optimizing node_module file size

Currently, I'm developing 2-3 react applications and noticed that every time I run npm install, it ends up downloading numerous dependencies into the cumbersome "node-modules" folder, totaling around 250-300mb in size! This large size makes it challen ...

Creating numerous pre-signed URLs using an Application Programming Interface

An API has been developed to generate pre-signed URLs for files stored in a private S3 bucket. The goal is to store these URLs in an array for access from another application. ["FILE1 pre-signed URL", "FILE2 pre-signed URL", etc..] However, there seems to ...