javascript - Unable to get simple focus() function working -
have simple contact link in nav bar listens click, triggers function focus() on form input id 'hello'. getting error:
uncaught typeerror: cannot read property 'addeventlistener' of null @ practice1.js:18 <nav> <ul> <li><a href="#home"><span class="active">home</span></a></li> <li><a href="#about">about</a></li> <li><a href="#media">media</a></li> <li><a href="#contact" id="hello">contact</a></li> </ul> </nav> <form> full name:<br> <input type="text" name="fullname" id="fullname"><br> message:<br> <textarea type="text" name="message" id="sidebar-message"></textarea><br> <button type="submit" name="message-submit" class="submit-button" href="#">submit</button> </form> function contactfocus() { $('#fullname').focus(); } var contactlink = document.getelementbyid('hello'); contactlink.addeventlistener('click', contactfocus, false);
this might timing problem: line runs before page executes.
try this, in more jquery-y idiom:
$(() => { $("#hello").click(contactfocus); }); edit:
in more detail, underlying problem javascript run before page has rendered, item id "hello" not yet exist.
my changes are
- i arranged function run once jquery ready; that's meaning of
$(fcn)expression. in opinion, superior using$(document).ready()-- document being ready not understood concept. point jquery ("$") ready. - i used
$("#hello")instead ofdocument.getelementbyid('hello'), equivalent, former jquery way it. - for same reason, used
.click(f)instead of.addeventlistener('click',f)
Comments
Post a Comment