Programming Tutorials

(追記) (追記ここまで)

Show and hide links based on button click

By: Niraj in Javascript Tutorials on 2023年04月17日 [フレーム]

Here is a code snippet that should show and hide the links based on the button clicked:

<!DOCTYPE html>
<html>
<head>
<title>Links</title>
<style>
.links {
display: none;
}
</style>
</head> <body><div><button onclick="toggleLinks('category1')">Category 1</button><button onclick="toggleLinks('category2')">Category 2</button><button onclick="toggleLinks('category3')">Category 3</button><button onclick="toggleLinks('category4')">Category 4</button><button onclick="toggleLinks('category5')">Category 5</button><button onclick="toggleLinks('category6')">Category 6</button><button onclick="toggleLinks('category7')">Category 7</button></div><div class="category1 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><div class="category2 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><div class="category3 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><div class="category4 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><div class="category5 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div> <div class="category6 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><div class="category7 links"><a href="#">Link 1</a><a href="#">Link 2</a><a href="#">Link 3</a><!-- Add more links as needed --></div><script> function toggleLinks(category) { var links = document.getElementsByClassName('links'); for (var i = 0; i < links.length; i++) { if (links[i].classList.contains(category)) { if (links[i].style.display === 'block') { links[i].style.display = 'none'; } else { links[i].style.display = 'block'; } } else { links[i].style.display = 'none'; } } } </script></body></html>

This code uses the display CSS property to hide and show the link divs based on the category button clicked. When a button is clicked, it loops through all the link divs and only shows the links in the selected category, while hiding the links in all other categories.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /