Modification of href value based on click event

We can mofify the href value according to our requirement based on any click events.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#w3s").attr("href", function(i, origValue){
      return origValue + "/jquery/"; 
    });
  }); 
});
</script>
</head>
<body>

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Change href Value</button>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>
</html>

Here we have a href which redirects to a page and we have a button for which we have created an event in which when this button is clicked the href changes to different href and hence when clicked on the changed href we get redirected to different page.

In this way we can modify the href according to our need.

Leave a comment

Your email address will not be published. Required fields are marked *