I use a Modernizr media query in JavaScript to change an element margin and add a class "small". My Modernizr media query doesn't work when I resize my browser, but when I refresh the page then it works. I know I can solve this problem using the jQuery $( window ).resize() function, but I want to solve it using a media query. Can any one tell me how I can solve this problem?
<html class="no-js">
<head>
<title>Foundation 5</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="modernizr.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if (Modernizr.mq('(max-width: 767px)')) {
$("#secondary").addClass("small");
$("#secondary").css("margin", " 25px");
}
});
</script>
<style type="text/css">
#primary {
width: 300px;
height: 200px;
background-color: black;
}
#secondary {
margin: 0 auto;
width: 250px;
height: 150px;
background-color: white;
position: absolute;
}
</style>
</head>
<body>
<div id="primary">
<div id="secondary">
</div>
</div>
</body>
</html>
At the moment it runs once only (on page load), so of course it only changes when you refresh the page.
Solution: You need your code to run onload and when the browser/window resizes. :
e.g.
<script type="text/javascript">
var mod = function(){
if (Modernizr.mq('(max-width: 767px)')) {
$("#secondary").addClass("small").css("margin", " 25px");
} else {
// Clear the settings etc
$("#secondary").removeClass("small").css("margin", ""); // <<< whatever the other margin value should be goes here
}
}
// Shortcut for $(document).ready()
$(function() {
// Call on every window resize
$(window).resize(mod);
// Call once on initial load
mod();
});
</script>
Option 2
A common alternative I now use is to simply trigger a window resize event at the end of the onload (e.g. after the handler is connected).
<script type="text/javascript">
// Shortcut for $(document).ready()
$(function() {
// Call on every window resize
$(window).resize(function(){
if (Modernizr.mq('(max-width: 767px)')) {
$("#secondary").addClass("small").css("margin", " 25px");
} else {
// Clear the settings etc
$("#secondary").removeClass("small").css("margin", ""); // <<< whatever the other margin value should be goes here
}
}).resize(); // Cause an initial widow.resize to occur
});
</script>
Simple JSFiddle example: http://jsfiddle.net/TrueBlueAussie/zv12z7wy/
Great answer above in Option 2
Helped me immensely as I was having the same issue of not seeing my changes reflect on initial page resizes. Causing the initial window.resize saves the day.
Just to make the above solution in Option 2 a little cleaner I created a mediaQ variable which I store inside the if statement. This un clutters the if statement. I also store your #secondary id inside a variable.
$(window).resize(function(){
var mediaQ = Modernizr.mq('only screen and (max-width:767px)');
var secondaryId = $("#secondary");
// if mediaQ is true
if(mediaQ){
secondaryId.addClass("small");
secondaryId.css("margin", " 25px");
// if mediaQ is false
} else {
secondaryId.removeClass("small");
secondaryId.css("margin", "");
}
}).resize();
Related
I've replaced my mouse pointer with a css element (".cursory"). Now it's a little green circle. I've put up a timer that detects when the mouse is idle for 2 seconds. I want to change the green color to red when the mouse is idle, but I can't figure out how to get ("cursory").css(...) to work. Below is my code, the problem .css() is in the goInactive function:
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><!--this is the jQuery document link-->
<script>
// this is where jQuery functions go
//TESTING IF THE UI IS IDLE
var TimeoutID;
function inputdetect() {
// attaches event handler to specified event
// takes event as string, function to run, and optional boolean
// to indicate when the event propogates
// these are false, so events "bubble up"
this.addEventListener("mousemove",resetTimer,false);
this.addEventListener("mousedown",resetTimer,false);
this.addEventListener("mousewheel",resetTimer,false);
this.addEventListener("keypress",resetTimer,false);
this.addEventListener("touchmove",resetTimer,false);
this.addEventListener("DOMmousescroll",resetTimer,false);
this.addEventListener("MSpointermove",resetTimer,false);
startTimer();
}
inputdetect();
function startTimer() {
//waits two seconds before calling inactive
TimeoutID = window.setTimeout(goInactive,2000); // does it need to take the window variable??
}
function resetTimer(e) {
window.clearTimeout(TimeoutID);
goActive();
}
function goActive() {
//what happens when the UI is not idle
$('p').text("The UI is not idle.");
startTimer();
}
function goInactive() {
$('p').text("The UI is idle.");
// REPLACING CURSOR WHEN UI IS IDLE
//this part won't work
$('cursory').css("background-color","red");
}
// THIS changes the pointer to a css element
$(document).ready(function() {
$(document).on('mousemove', function(e) {
$('.cursory').css({
left: e.pageX,
top: e.pageY
});
});
});
</script>
</head>
<style>
/*this is where CSS styling goes*/
html {
cursor: none;
}
.cursory {
height: 10px;
width: 10px;
border-radius: 100%;
background-color: green;
position: relative;
}
</style>
<body>
<div class = "cursory"></div>
<!--this is where the HTML will go*/-->
<p>hello</p>
cursory is the class of the element, use class selector .className
$('.cursory').css("background-color","red");
Propably the problem is missing "." ...
$('.cursory').css("background-color","red");
A little article about selectors for you:
http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Based on the code you have above, it looks like your not using the appropriate CSS selector in your jQuery call.
Change this
$('cursory').css("background-color","red");
to
$('.cursory').css("background-color","red");
I'm trying to adapt this JSFiddle to make the menu button on my website hide when I'm at the top of the page and show when I start scrolling down.
I modified the JS to match the CSS on my site. Then I placed it in tags in the head of my page
var $scb = $('<div class="toggle-menu-wrap"></div>');
$('.top-header').append($scb);
var $ccol = $('.content');
$ccol.scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
However, it still doesn't work. Am I making a mistake in how I'm modifying the JS to fit my CSS?
You can include the toggle-menu-wrap element in your HTML from the start. There is no need to insert it using JS.
Write the one line of CSS you need, which is to hide the element from the beginning
.toggle-menu-wrap {
display: none;
}
Your version of jQuery uses 'jQuery' instead of '$' to reference itself. I would also re-write your JS like:
jQuery(document).ready(function() {
fadeMenuWrap();
jQuery(window).scroll(fadeMenuWrap);
});
function fadeMenuWrap() {
var scrollPos = window.pageYOffset || document.documentElement.scrollTop;
if (scrollPos > 300) {
jQuery('.toggle-menu-wrap').fadeIn(300);
} else {
jQuery('.toggle-menu-wrap').fadeOut(300);
}
}
Like #murli2308 said in the comments above, you need to attach a scroll event listener to the window:
$(document).ready(function () {
var $scb = $('<div class="scroll-border"></div>');
$('.above').append($scb);
var $ccol = $('.content');
$(window).scroll(function(){
$scb.stop(true,true).fadeTo(500, $ccol.scrollTop() > 10 ? 1 : 0);
});
})
Wrapping your code in $(document).ready() would also be a good idea.
The reason $ccol.scroll(function() { ... works in that fiddle is because of the CSS:
.content{
height: 200px;
width: 200px;
overflow: auto;
}
Notice overflow: auto;. This causes that specific div to be scrollable. However, on your website, you scroll the entire page, not $ccol. This means the event handler will never fire a scroll event (since $ccol will never scroll).
You might have forgotten to link Jquery.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Link this inside your head tag incase.....
This should do the job:
$(window).scroll(function(e){
if ($(this).scrollTop() > 0) {
$(".your_element").css("display", "block");
} else {
$(".your_element").css("display", "none");
}
});
Firstly - i'm not even sure if the syntax is correct, but what i'm trying to do is, i have a div showing an animated image sequence which picks a position using a variable.
I will eventually use JSON to feed the value being changed, but for now i'm just trying to understand how to use JQuery to change the variable. Here's the code:
<div id="noiseAnimDiv" style="float: center; background-color: #ffffff; ">
<script type="text/javascript" src="./animatedpng.js">
</script>
<script type="text/javascript">
var stoptheClock = 3;
noiseAnim = new AnimatedPNG('noise', './noise/noise0.png', 8, 50);
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock, 1000); //spin yet stay on value 3
</script>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
</script>
Any help much appreciated
code is live btw at so you can at least see the animation seq
http://ashleyjamesbrown.com/fgbp/noise.htm
The AnimatedPNG library you are using only checks the variable's value once - when initialized. in your code, you are changing the value after initializing it.
$(document).ready(
function() {
$("#stoptheClock").val(6); //
}
);
Should be
function() {
stoptheClock = 6;
noiseAnim.draw(false);
noiseAnim.setFrameDelay(stoptheClock,1000);
}
You are not using JQuery for any useful cause in your code, therefore I have removed all of the Jquery parts.
I want to create a function for showing pop or status when user typing something in field, I want to do it without submitting form, I have try following function but its not working properly can anyone let me know where the problem..........?
Javascript
<script type="text/javascript">
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
</script>
HTML
<input type="text" name="text" id="confirm">
Just listen to the onkeyup and onkeydown events. I included a jsfiddle that might help.
jsfiddle
Edit - The Latest Update
Okay, I see you've got your fiddle from Vivek, but you might be interested in this as well. Now I get completely what you want to achieve, and here's a short description. The best practice is to split JavaScript from HTML and avoid putting JavaScript inside HTML head and body as much as you can.
So, first create three files: Test.js Example.html and Test.css. Of course, you also need jQuery file which you just include here inside the head. In Example.html put the following code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="Test.css"/>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript" src="Test.js"></script>
</head>
<body>
<input type="text" id="test"/><span id="popup"></span>
</body>
</html>
In Test.css add some style to your pop-up span element (you could also use division element and style it to your liking if you want fixed height and width, add shadows and so on):
#popup {
background-color: red;
color: white;
display: none;
}
And finally, put the following JavaScript code in Test.js:
$(document).ready( function() {
$("#test").keyup( function() {
if($("#test").val().length>5) {
$("#popup").fadeIn();
$("#popup").html("Invalid length. Maximum is 5.");
}
else {
$("#popup").fadeOut();
}
});
});
By dividing JavaScript, CSS and HTML into separate files, you get much tidier HTML and separated styling and client-side logic from markup.
Old Answer
Wrap the code inside $(document).ready().
Like this:
$(document).ready(function() {
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
});
function checkFile(e) {
if ($('#confirm').val().length > 0) {
alert("txt");
}
}
Also, addEventListener is not available in IE8 and below. You could use the onchange event, like this:
$(document).ready(function() {
document.getElementById("confirm").onchange = checkFile;
});
There is a similar method for IE8 and earlier called attachEvent. In case of using the attachEvent method, it would look something like the following:
$(document).ready(function() {
document.getElementById('confirm').attachEvent('change', checkFile);
approveletter.attachEvent('change', checkFile);
});
You could also use the jQuery.change() as suggested in the comments by Protron:
$(document).ready(function() {
$("#confirm").change(function() {
if ($('#confirm').val().length > 0) {
alert("txt");
}
});
});
And of course it's possible to do it without the classic alert pop-up window. You could create your own HTML division element with display:none and show it when necessary. Just send me a note in the comments if you need instructions on that as well.
Using this, you need not click the web page.
<input type="text" name="text" id="confirm"><br /><br />
<span id="status" ></span>
<script type="text/javascript">
$('#confirm').keyup(function () {
if ($('#confirm').val().length > 0) {
$('#status').html("Text entered");
}
else
{
$('#status').html("Text removed");
}
}
)
</script>
Why does the handler bound to an event of an element fire the wrong result? I would expect the click event of Div1 below to popup a dialog stating 'div1' but it popup's 'div2'.
I am new to this and I am scratching my head to work out why this is happening. I would appreciate any help to explain.
Cheers,
Alex
<!DOCTYPE html>
<html>
<head>
<title>TestEvents</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//Object Array
var objToTest = [{ TabName: "div1" },
{ TabName: "div2"}];
//Adds events to each div
function TestWhatIsGoingOn(myObjToTest) {
for (i in myObjToTest) {
$('#' + myObjToTest[i].TabName).click(function() { TestResult('TabName: ' + myObjToTest[i].TabName); });
}
}
function TestResult(message){
alert(message);
}
$(document).ready(function() {
TestWhatIsGoingOn(objToTest);
});
</script>
<style type="text/css">
#div1, #div2
{
border: solid thin black;
height: 100px;
width: 300px;
}
</style>
</head>
<body>
<div id='div1'>div1; click here to show expected result: 'TabName: div1'</div>
<div id='div2'>div2; click here to show expected result: 'TabName: div2'</div>
</body>
</html>
it seems a classic closure problem, because when you click on div (any) i variable has already reach the end of for loop (so it always prints the last value). Try to change like so
function TestWhatIsGoingOn(myObjToTest) {
for (i in myObjToTest) {
(function(i) {
$('#' + myObjToTest[i].TabName).click(function() { TestResult('TabName: ' + myObjToTest[i].TabName); });
)(i);
}
}
Your problem is in this section of code:
for (i in myObjToTest) {
$('#' + myObjToTest[i].TabName).click(function() {
TestResult('TabName: ' + myObjToTest[i].TabName);
});
}
The trouble is that the value of i is not hard-coded into this section. When the function runs, it will see what the current value of i is. Since you have since incremented it to refer to your second tab, this function will always refer to the second tab. This feature of Javascript is called a closure -- it closes in the value of i.
The easiest way around this is to use jQuery to bind to more than one object at once, and then evaluate based on the object clicked on:
$(document).ready(function(){
$('div').click(function(){
alert('TabName: ' + this.id);
});
});
This will do everything you want your code in the question to do.
In a real-world situation, you would probably need to give the divs a common class (e.g. toClick) and then use a jQuery class selector ($('.toClick')).