html - Javascript: Display contents of one div, make others invisible -
i'm trying write function takes in id of div, checks id against list of other ids, displays div relevant passed-in id, , causes other divs ids in list not displayed.
<script type="text/javascript"> function display_page(id) { //list of ids want check against var pages = ['home', 'about', 'listen', 'more']; (var i=0; i<pages.length; i++) { var e = document.getelementbyid(pages[i]); if (pages[i] == id){ e.style.display = 'block'; alert(e); } else{ e.style.display = 'none'; alert(e); } } </script> and function calls structured this:
<li class="active" class="test"><a href="#" onclick="display_page('home');">home</a></li> not sure why isn't working -- note, ids unique don't think that's issue. alerts not showing though upon clicking relevant links (like 1 posted above). help!
you can utilize queryselectorall help here:
function display_page(id) { var pages = document.queryselectorall('#home, #about, #listen, #more'); (var i=0, ilen=pages.length; i<ilen; i++) { pages[i].style.display = pages[i].id == id? '' : 'none'; } } i wonder when iterator added nodelist interface can do:
var id = 'home'; document.queryselectorall('#home, #about, #listen, #more').foreach(function(el) { el.style.display = el.id == id? '' : 'none'; }); note toggling between 'none' , '' (empty string) preferred element adopts default or inherited style , don't have hard–code might be.
oh, without qsa:
function display_page(id) { var ids = ['home', 'about', 'listen', 'more']; (var i=0, ilen=ids.length; i<ilen; i++) { page = document.getelementbyid(ids[i]); page.style.display = page.id == id? '' : 'none'; } } this 1 depends on es5 foreach:
function display_page(showid) { ['home', 'about', 'listen', 'more'].foreach(function(id) { var page = document.getelementbyid(id); page.style.display = page.id == showid? '' : 'none'; }); } javascript html
No comments:
Post a Comment