James Anderson James Anderson - 3 months ago 8
HTML Question

JQuery .width won't work within my if statement

My problem is that for some reason my .width wont work and I can't figure out why. JQuery is referenced correctly in the html file and the id is correctly inserted. (I think :/ sorry if this is just a rookie mistake as i believe it is. however i have looked around for a solution and as of yet have found one.) here is my JavaScript.

window.onload;
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
if(detectmob()){
window.alert('success');
$('#content').width("100%");
} else {
window.alert('fail');
}


and here is my html.

<!DOCTYPE html>
<html>
<head>
<title>Autofresh</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script type="text/javascript" src="styles/jquery-3.1.0.min.js"></script>
<script src="styles/main.js"></script>
</head>
<body>
<div id="content">
<div id="header">
//image goes here
<div id="navbar">

</div>
</div>
<div id="video"></div>
<div id="registration">

</div>
</div>
</body>
</html>


Any help is much appreciated as I am still in the process of learning JavaScript and JQuery and am by no means an expert, quite the opposite. Thank you in advance for any help that is given.

Answer

Okay I made some minor changes the first is navigator.userAgent.match(/Mozilla/i) so you can test it from a browser, you might want to remove that later on. The second is I moved the JQuery reference into the body, I also wrapped the JavaScript in a document.ready. Hope that helps

$(document).ready(function() {
    if(detectmob()){
      console.log("success");
      $('#content').width("100%");
    } else {
      console.log("navigator.userAgent");
    }
});

https://jsfiddle.net/63nm4cxs/

$ is undefined.

This was your main issue, JQuery wasn't referenced!