I'm currently busy with creating a login form that slides down when a certain login button gets pressed. I've got this working by using the following code:
$(document).ready(function (){
$('.loginButton').click(function(){
$('.login').slideToggle();
});
});
The HTML I made for the login form looks like this:
<main>
<div class="login">
<h5>Log in here</h5>
<form>
<label for="username">Username:</label>
<input type="text" id="username" required>
<label for="password">Password:</label>
<input type="password" id="password" required>
<p class="registertext">Click <a href="register.html">here</a> to register!</p>
<input type="submit" value="Sign in">
</form>
</div>
</main>
The problem I stumble upon now is that my website currently uses four HTML pages. So in each of the HTML files of them the above HTML code is present. Now I want to get rid of this duplicate code, but I don't really know what's a good and efficient way to do this. I've already tried some things myself that worked, but I'm not sure whether they are efficient. The first thing I did was appending the HTML code inside the div to the div once the login button gets pressed, I only let this happen once by the once of a Boolean.
var firstTime = true;
$(document).ready(function (){
$('.loginButton').click(function(){
if (firstTime) {
$('.login').append('<h5>Log in here</h5><form><label for="username">Username:</label><input type="text" id="username" required><label for="password">Password:</label><input type="password" id="password" required><p class="registertext">Click <a href="register.html">here</a> to register!</p><input type="submit" value="Sign in"></form>');
firstTime = false }
$('.login').slideToggle();
});
});
Another solution I found was putting the code within the div inside a separate HTML file and load that file into the div.
$(document).ready(function (){
$('.login').load(login.html);
$('.loginButton').click(function(){
$(this).toggleClass('active');
$('.login').slideToggle();
});
});