I have this giant wall of code, which replaces the src of an img on the page with the one specified, for each link in a nav menu.
But... it's a giant wall of code, calling up the action for each individual ID tag. There's got to be a better way to do this, right? Am I missing something? Is there a way I can have a formula parse which ID was clicked, and use that ID like, "ID.png" (replacing ID with the ID in question)?
$(document).ready(function(){
<!-- Get Timestamp -->
var _c = new Date().getTime();
<!-- Current Day -->
$('#current').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/diary.png?c='+_c);});
$('#diary').attr('src', 'https://mywebsite.com/diary/diary.png?c='+_c);
<!-- April 2022 -->
$('#20220422').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220422.png?c='+_c);});
$('#20220423').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220423.png?c='+_c);});
$('#20220424').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220424.png?c='+_c);});
$('#20220425').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220425.png?c='+_c);});
$('#20220426').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220426.png?c='+_c);});
$('#20220427').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220427.png?c='+_c);});
$('#20220428').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220428.png?c='+_c);});
$('#20220429').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220429.png?c='+_c);});
$('#20220430').click(function(){$('#diary').attr('src', 'https://mywebsite.com/diary/stored/20220430.png?c='+_c);});
<!-- this goes on for the remainder of the year, but I'm cutting it short here so that this post doesn't think it's spam -->
})
-
\$\begingroup\$ The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see How to Ask for examples, and revise the title accordingly. \$\endgroup\$Mast– Mast ♦2022年04月28日 20:09:04 +00:00Commented Apr 28, 2022 at 20:09
1 Answer 1
You can have some util methods to generate based on date.
function dairyAttr(date) {
return function () {
$("#diary").attr(
"src",
`https://mywebsite.com/diary/stored/${date}.png?c=` + _c
);
};
}
function setClick(date) {
$(`#${date}`).click(dairyAttr(date));
}
const dates = ["20220422", "20220423"];
dates.forEach(setClick);