Detaching and AppendingTo on Window Resize - javascript

So I am trying to detach and appendTo a div based on window size. The following is what I currently have.
I am creating a function with a variable SOCIALBAR assigning it equal to #SOCIALMEDIA and detaching it. Then based on window size for (document).ready and (window).resize, I call the SOCIALBARPlACEMENT function and #SOCIALMEDIA is either appendeto the #TOP or #LEFT divs.
This works fine and dandy on (document).ready but does not work for (window).resize.
In fact, if I remove document.ready, and leave window.resize, the function still runs on page load, but doesn't work on page resize.
Any thoughts would be appreciated. Thank!
function socialbarplacement() {
var socialbar;
socialbar = $("#socialmedia").detach();
if (jQuery(window).width() < 1384) {
socialbar.appendTo("#top");
} else {
socialbar.appendTo("#left");
}
};
$(document).ready(socialbarplacement());
$(window).resize(socialbarplacement());

You are calling the functions immediately rather than passing them as event handlers, try:
$(document).ready(socialbarplacement);
$(window).resize(socialbarplacement);
/*
someFunction() <-- invokes the function and resolves to the returned value
someFunction <-- resolves to the function reference
*/

I would probably do something along these line (untested code):
$(window).resize( function(){
var wnd = $(window), soc = $('#socialmedia');
return function(){
// might add a check to make sure you are not appending to the current parent.
soc.appendTo( $(window).width() > 1384 ? '#left' : '#top');
}
});
Resize will get fired when the page loads so you don't need to have both on ready and resize.
Also looking at it, you are executing the method when you really should be passing it in by name.

I,ve try like this... Enjoy!
$(function () {
if (matchMedia) {
var mq = window.matchMedia('(max-width: 1384px)');
var socialmedia = $("#socialmedia");
mq.addListener(WidthChange);
WidthChange(mq);
}
function WidthChange(mq) {
if (mq.matches && socialmedia) {
socialmedia.appendTo("#top");
socialmedia = null;
} else {
socialmedia = $("#socialmedia").detach();
socialmedia.appendTo("#left");
}
};
});
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top">
<div id="socialmedia">SOCIALMEDIA</div> <br>
**TOP**
</div>
<div id="left">
<br>
**LEFT**
</div>
</body>
</html>

Related

Waiting with $(document).ready, $(element).ready, and windows.load all trigger before content is ready

Would you please help me delay execution of my function until the content has loaded? I've streamlined my code to the essentials, bear with my typos:
function Phase1()
{
$(".Hidden").load("hidden.html");
$(window).load(Phase2());
/* I've also tried $(document).ready(Phase2()); */
/* and $(."Hidden").load("hidden.html",Phase2()); */
/* and window.onload... */
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
The Random class contains several items. On the first pass the alerts are never called (length is 0), on the 2nd iteration it's had time to load everything.
I see no errors in the console when executing.
I have a small and neat solution for your problem, all you need to do is,
Call a setInterval for very short span to check the element is present in DOM or not, if its not your interval will go on, once the element is present, trigger your functions and clear that interval.
code will look like this..
var storeTimeInterval = setInterval(function() {
if (jQuery('.yourClass').length > 0) {
//do your stuff here..... and then clear the interval in next line
clearInterval(storeTimeInterval);
}
}, 100);
The page will load the elements from top to bottom.
If you want your JS code to execute after all elements have loaded, you may try any of the following:
Move your script to the bottom of the page.
<html>
<head></head>
<body>
<!-- Your HTML elements here -->
<script>
// Declaring your functions
function Phase1()
{
$(".Hidden").load("hidden.html");
}
function Phase2()
{
var Loop;
var Source_Array = document.getElementsByClassName("Random");
for (Loop=0;Loop<Source_Array.length,Loop++)
{ alert(Source_Array[Loop].innerHTML; };
}
// Executing your functions in that order.
Phase1();
Phase2();
</script>
</body>
</html>
Bind your functions to document ready using Vanilla JS.
document.addEventListener("DOMContentLoaded", function() {
Phase1();
Phase2();
});
Bind your functions to document using jQuery.
$(document).ready(function() {
Phase1();
Phase2();
});

Unbeleivable, same Javascript code do not behave the same way in JSFiddle

I wrote the same code in two JSFiddle, and they do not behave the same way :
HTML:
<p id='complete'></p>
JS:
document.onreadystatechange=fnStartInit;
function fnStartInit()
{
var state = document.readyState
if (document.readyState === 'complete')
{
document.getElementById('complete').innerHTML = 'Document completely loaded'
}
}
Working JSFiddle: https://jsfiddle.net/Imabot/toujsz7n/9/
Non working JSFiddle: https://jsfiddle.net/Imabot/3sLcpa0y/7/
Why do they not behave the same way?
Your first link has the load setting "No wrap - bottom of <head>".
This is equivalent to having HTML like
<head>
<script>
// YOUR SCRIPT HERE
</script>
<head>
<body>
// YOUR HTML HERE
</body>
Your second link has the load setting "On Load":
This is equivalent to having HTML like
<head>
<script>
window.onload = function() {
// YOUR SCRIPT HERE
}
</script>
<head>
<body>
// YOUR HTML HERE
</body>
You can see this if you Inspect the iframe in the lower right. So by the time the second script runs, readystatechange never fires again, so fnStartInit never runs.
Here's a Stack Snippet demonstrating the same problem:
window.onload = () => {
console.log('onload');
document.onreadystatechange = () => {
console.log('ready state just changed');
};
};

In jQuery unable to unbind an added function

I'm trying to add a function to an element. Later I'm trying to remove that function. It's not working in jQuery.
var myFunction=function(element){
$(element).animate({
/* Some Code in here */
});
myFunction(element); // I want in a loop
}
/* No issues with the function */
/* binding this function in another place */
$(otherElement).on('focus', myFunction);
/* In another location I want to off the focus on the element */
$(otherElement).on('focus'); --> This is not working. My expectation is the animation to be stopped.
I have tried with live/die and bind/unbind too, but no luck.
Wow, it's just an argument error.
var myFunction=function(element){ ---> you just expect an dom element as argument. But $(otherElement).on('focus', myFunction);, what is passed to myFunction is a jQuery Event object, not dom element.
So, try this:
$(otherElement).on('focus', function(ev/*this is event, not element*/) {
myFunction(this);
});
And if you want to unbind event, just use $(otherElement).off('focus');
Try
var myFunction = function(element) {
var $element = $(element).animate({
height: 'toggle'
}, {
done: function() {
var flag = $element.data('stopAnimation');
if (flag) {
$element.removeData('stopAnimation');
return;
}
myFunction(element);
}
});
// I want in a loop
}
$('#otherElement').on('focus', function() {
myFunction($('#element'))
});
$('#otherElement').on('blur', function() {
$('#element').stop(true, true).data('stopAnimation', true);
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>
<input id="otherElement" />
<div id="element">element</div>
Note: I don't know whether it is the optimal solution

I can't figure out how to get my javascript onclick event to work

When I click on the button nothing happens unless I call the function in the html. I am trying to remove all inline javascript. I have included the commented-out section of html that works. Thanks in advance for the help!
JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. Change this:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example.
You have to add your whole code inside load, like this
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or
document.getElementById("sayHi").onclick = writeOutput;
You have two issues.
The first being covered by jbabey.
The second is that firstScript.js appears before your button. This is problematic as when you are assigning the onClick handler to it. It doesn't exist in the dom.
Try putting the entire main script inside window.onload = function () { ... } or moving it to the bottom of the markup.

How do I recognize a mouseclick in a webpage from a Safari extension?

I'm a bit of a noob, but I tried all of the obvious things. Perhaps my javascript is just terrible and that's why, but onmousedown = func; doesn't work. etc.
function performCommand(event)
{
/*removed*/
//It reaches this point
document.body.onclick = function() {
//Never reaches this point
/*removed*/
}
}
https://developer.mozilla.org/en/DOM/element.onclick
Summary
The onclick property returns the onClick event handler code on the current element.
Syntax
element.onclick = functionRef;
where functionRef is a function - often a name of a function declared elsewhere or a function expression. See Core JavaScript 1.5 Reference:Functions for details.
Example
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript">
function initElement()
{
var p = document.getElementById("foo");
// NOTE: showAlert(); or showAlert(param); will NOT work here.
// Must be a reference to a function name, not a function call.
p.onclick = showAlert;
};
function showAlert()
{
alert("onclick Event detected!")
}
</script>
<style type="text/css">
#foo {
border: solid blue 2px;
}
</style>
</head>
<body onload="initElement()";>
<span id="foo">My Event Element</span>
<p>click on the above element.</p>
</body>
</html>
Or you can use an anonymous function, like this:
p.onclick = function() { alert("moot!"); };
(From the MDC # cc-by-sa.)

Categories

Resources