James Anderson James Anderson - 3 months ago 10
CSS Question

Jquery .width wont work within my if statement

my problem is that for some reason my .width wont work and i cant figure out why Jquery is linked above my java script file 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 file contents.

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 java script 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!

Comments