Without storing the state on a server, you need to use sessionStorage
or localStorage
SUBSTANTIAL UPDATE: I realize you are also using color
while you should be using background-color
. Using $(document).ready()
and jquery:
<script type="text/javascript">
$( document ).ready(function() {
if(localStorage.getItem('isCliked'){
$('#mylink').css('background-color','green');
}
$('#mylink').on('click',function() {
$('#mylink').css('background-color','green');
// set the value upon clicking
localStorage.setItem('isCliked', true)
});
});
</script>
Also, since you are using Bootstrap, you could use the class manipulation from jquery
<script type="text/javascript">
$( document ).ready(function() {
if(localStorage.getItem('isCliked'){
$( "#mylink" ).addClass( 'btn-success' );
$( "#mylink" ).removeClass( 'btn-default' );
}
$('#mylink').on('click',function() {
$( this ).addClass( 'btn-success' );
$( this ).removeClass( 'btn-default' );
// set the value upon clicking
localStorage.setItem('isCliked', true)
});
});
</script>
Important: this solution will not work if the user changes devices, since the button state is stored locally. If you want a strong solution, you need to store the state on the server.
$('#mylink').on('click',function() {
<AJAX CALL TO SERVER TO STORE STATE>
});
In such case, your initial button rendering should already take this into account (check on server before serving your <a>
) -or- you will need another ajax call upon $(document).ready()
. It depends on your design and requirements.
<script type="text/javascript">
$( document ).ready(function() {
<AJAX CALL TO QUERY THE SERVER ABOUT THE BUTTON STATE>
<RENDER BUTTON ACCORDING TO RESULTS>
$('#mylink').on('click',function() {
<AJAX CALL TO SERVER TO STORE STATE>
});
});
</script>