This blog will discuss the functionalities of the stated href expression “<a href=”javascript:;”></a>”.
What Does href Expression “<a href=”javascript:;”></a>” Do?
The href attribute in an HTML “<a>” tag typically specifies the URL or web page that the link is directed to.
In the case of “<a href=”javascript:;”></a>”, the href attribute is set to “javascript:;” which is a placeholder value that does nothing when clicked. This is often used when the link is being used for a JavaScript function or event and does not need to redirect the user to a new page.
The “javascript:;” is the most impressive feature of JavaScript to integrate it with HTML and CSS. It helps to call the JavaScript functions in an HTML href or anchor tag.
Example
In the given example, display the image on the current page by clicking on the link using “javascript:;” in the href attribute that will prevent the browser from leaving the current page:
<a href="javascript: img = document.createElement('img');
img.src = 'sun.jpg';
src = document.getElementById('myImg');
src.appendChild(img);">Show Image</a>
In the above code:
- First, create a div element in the HTML file, and assign an id “myImg”.
- Set the href attribute to “javascript:;” and create an “img” element utilizing the “createElement()” method.
- The “src” attribute will indicate the path of the image.
- Get the reference of the image element on the HTML file to show the image using the “getElementById()” method.
- Append the image as a child element using the “appendchild()” method.
The output indicates that the image will be displayed on the same page while clicking on the link:
You can also access the function in the href <a> tag with “javascript:;” placeholder:
<a href="javascript:myFunction();">Click Me</a>
Define a function “myFunction()” in the <script> tag that is accessed in the href <a> tag:
function myFunction(){
let img = document.createElement('img');
img.src = 'sun.jpg';
src = document.getElementById('myImg');
src.appendChild(img);
}
</script>
Output
That was all about the working of the “<a href=”javascript:;”></a>” expression.
Conclusion
The href expression “<a href=” javascript: ;”></a>” helps to call the JavaScript functions in an HTML href/anchor <a> tag to prevent the browser from navigating away from the current page. It is the most impressive feature of JavaScript to integrate it with HTML and CSS. This blog discussed the functionality of the stated href expression “<a href=”javascript:;”></a>”.