Change of weekly scheduled date for hyperlink url

Each week, I release a newsletter with a consistent file path and similar file name except for the date. The newsletter is published every 7 days, requiring me to update the link by adding 7 days to the date each time. It's important that the date is included in the file name, so simply naming it "newsletter" won't suffice; it needs to be ".../newsletter-DDMMYY.pdf"

<a href="/newsletter-040314">Weekly Newsletter</a>

Is there a way to use javascript to automatically adjust the date in the URL above on a weekly basis?

Answer №1

Providing a JavaScript-based solution

<body>
    <a id="newsletter">Weekly Newsletter</a>

    <script>
        function fetchNewsletterDate () {
            var DAY_OF_NEWSLETTER = 6 // 0 for Sunday, 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday, 6 for Saturday
            var day = 24 * 60 * 60 * 1000;
            var date = new Date();
            var dayOfWeek = date.getDay();
            date = new Date(date.getTime() - (dayOfWeek - DAY_OF_NEWSLETTER) * day);
            if (date > new Date()) date = new Date(date - 7 * day)
            return date;
        }

        function modifyNewsletterLink() {
            var date = fetchNewsletterDate();
            var link = document.getElementById('newsletter');
            var href = '/newsletter-' + ('0' + date.getDate()).slice(-2) + ('0' + (date.getMonth() + 1)).slice(-2) + (''+date.getYear()).slice(-2);
            link.href = href;
        }

        modifyNewsletterLink();
    </script>

</body>

Answer №2

time.js is a fantastic tool for handling date manipulations:

If you need to add 7 days to a specific date:

time("040314", "DDMMYY").add('d',7).format("DDMMYY")

Alternatively, if you want to add a week:

time("040314", "DDMMYY").add('w',1).format("DDMMYY")

The result will be the same:

"110314"

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

I am experiencing difficulties with broadcasting and attending events

File.js scope.menuItemClick = function (def, callbackText, keepMenuOpen) { console.log(def); if(def.automationId === "Print"){ console.log("before send"); $scope.$root.$broadcast("printingData","my Data"); console.log("after send"); } Nex ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Is there a way to expand jQuery quicksearch functionality to include searching for words with accents?

Hello everyone, I'm currently working on the development of this website using jQuery isotope, WordPress, and jQuery quicksearch. Everything is functioning perfectly, but I would like to enhance its functionality. For example, when I type "Mexico," I ...

Using async-await to handle an array of promises with the map method

I have come across several discussions on the same error but none of them solved my issue. Here is the code I wrote: const userOrganizationGroups = (organizationGroupsList) => { if (Array.isArray(organizationGroupsList) && organizationGroupsLi ...

Can you explain the distinction between firstChild and childNodes[1]?

Exploring the distinction between child nodes and child elements within JavaScript DOM: For instance, var myTbodyElement = myTableElement.firstChild; versus var mySecondTrElement = myTbodyElement.childNodes[1]; Is it possible to interchangeably use firs ...

What methods can be used to automatically direct users to a specific page in my app once they have completed the registration process?

It's possible that I'm not placing the second router.replace('/contact'); line correctly. However, it seems strange because the redirect works fine when a user logs in. Any help would be greatly appreciated. if (isLogin) { const r ...

Can someone help me identify the table rows that are adjacent to a dropped row in a jQueryUI Sortable setup?

My current setup involves using the jQueryUI Sortable plugin on a table, and thankfully everything appears to be functioning correctly. Both the HTML and JavaScript are passing validation. However, I am faced with the challenge of finding a way to identi ...

Having trouble with Axios PUT request not sending complete data to the server using JavaScript

One issue I'm encountering is that when sending an axios request with specific data, not all of the data gets updated in the user model. Here's a look at my code: Here is the Front-End code with axios request: import axios from "axios" ...

How to utilize a prepared statement in MySQL using NodeJS for inserting or updating data in a specific table?

Below is the code snippet I need assistance with: connection.query({ sql: 'CREATE TABLE ? ( `wage` FLOAT NOT NULL , `monday` FLOAT NOT NULL , `tuesday` FLOAT NOT NULL , `wednesday` FLOAT NOT NULL , `thursday` FLOAT NOT NULL , `friday`) ENGINE = InnoDB ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

The conditional statement in the given code snippet is failing to execute properly

const checkCondition = (props) => { let conditionMet = false; console.log('-----****----',props); if(props && props.isAllowed) { conditionMet = true; } if(someOtherCondition) { return( <li><Link className=" ...

Identify dead hyperlinks on a webpage with the help of selenium webdriver while steering clear of links that

I have been trying to identify broken links on a webpage by extracting all anchor tags. However, some of the links are dynamically generated through JavaScript. When I attempt to print out the list of all the links, I encounter a StaleElementReferenceExcep ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

What could be causing the malfunction in this JavaScript and WebRTC code?

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vid Chat App</title> </head> <body> <video controls autoplay> </video> <script src="https: ...

Updating deeply nested document in Mongoose

Is it possible to change the value of array1.array2.status, according to the schema provided below? const SomeSchema = new mongoose.Schema({ status: Boolean, array1: [{ array2[{ status: boolean }] }] }) ...

Converting Strings into Variable Names in Vue.js: A Step-by-Step Guide

Hi everyone, I was wondering if there's a way to convert a string into a variable name. For example, I want to convert "minXLabel" to minXLabel so that I can use it within span tags like this: <span>{{minXLabel}</span>. I current ...

Using webpack with the production parameter

Currently working on an Express+React application which utilizes webpack for bundling. During development, I have been using "webpack --watch", but as I prepare to deploy to production, I am interested in uglifying my JavaScript code. Unfortunately, the ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...

Tips for maintaining the state of a page submitted via Turbolinks using Rails 5 and jQuery

My current challenge involves toggling the visibility of a section when a specific element is clicked. Initially, I was able to achieve this functionality successfully. However, complications arose as my application revolves around a todo list where tasks ...

What is the Angular approach for configuring a form's encoding type to application/json?

I need to send form data using a POST request that triggers a download, making it impossible to use any Javascript requests. Therefore, calling a function with the $http service is not an option. Additionally, I require the corresponding backend route in ...