send height from javascript function to jquery - javascript

I'm calculating the height of an iframe using a JavaScript function and store it in a Variable, now I want to send that variable to jQuery to set the height().
My JavaScript function
function iframeLoaded()
{
var iFrameID = document.getElementById('ftwo');
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight;
}
The functions works fine because when I alert the value, it display it correctly, and I'm in the same domain that I'm calculating the height
$(document).ready(function(){
$("#ftwodiv").height(iFrameID);
});
on my body tag I have this:
<iframe id="ftwo" width="455px" onLoad="iframeLoaded()"
scrolling="no" frameborder="0" src="http://www.company.com"></iframe>
I tried some stuff that did not work.

You can return that from the function and use it.,.
function iframeLoaded(){
var hgt = 0;
var iFrameID = document.getElementById('ftwo');
hgt = iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight;
return hgt;
};
$(document).ready(function(){
var iFrameID = iframeLoaded();
$("#ftwodiv").height(iFrameID);
});
You can also use a Global variable to achieve the same..
var iFrameHeight = 0;
function iframeLoaded(){
var hgt = 0;
var iFrameID = document.getElementById('ftwo');
iFrameHeight = iFrameID.height = FrameID.contentWindow.document.body.scrollHeight;
};
$(document).ready(function(){
$("#ftwodiv").height(iFrameHeight);
});
But the first approach is cleaner

Related

Can't acces to the height of a div in an Iframe

here is my problem:
the size of my iFrame must vary according to the size of a div in it and when I try to get the size of this div everything I try returns 0
var childiFrame = document.getElementById("myDiv");
console.log(childiFrame,"here is my iframe");
var innerDoc = childiFrame.contentWindow.document;
console.log(innerDoc,"here is the innerDoc where i have to find my div");
mdDiv =innerDoc.getElementById("md");
console.log(mdDiv,"here is my div !");// and i can see the clientHeight =245
var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
console.log(divHeight,"the div height always equals 0 !");
I haven't seen anyone talk about this problem, so if anyone has any ideas, I'll take it!
Please put this script in the parent page -
<script>
window.addEventListener('message', function(e) {
var data = e.data.split('-'),
scroll_height = data[0],
iframe_id = data[1];
if(iframe_id == 'iframe1')
document.getElementById('iframe-container-1').style.height = scroll_height + 'px'; } , false);
</script>
Put this script in iframe
<script>
setInterval(function () {
window.top.postMessage(document.body.scrollHeight + '-' + 'iframe1', "*");
}, 500);
</script>
I think you need to wait for iframe to fully load first using the onload event, then try to access the mdDiv attributes like:
var childiFrame = document.getElementById("myDiv");
console.log(childiFrame, "here is my iframe");
childiFrame.onload = function() {
console.log('my iframe is loaded');
var innerDoc = childiFrame.contentDocument ? childiFrame.contentDocument : childiFrame.contentWindow.document;
console.log(innerDoc, "here is the innerDoc where i have to find my div");
mdDiv = innerDoc.getElementById("md");
console.log(mdDiv, "here is my div !");
var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
console.log(divHeight);
};

Load map from myshiptracking after page load

In addition to this topic execute a javascript after page load is complete I noticed the solution didn't work for loading a map. I do have a similar use case. However, if I follow the script the script needed doesn't load.
I want to load a map after the loading of the page is finished, however I do see the script in the page source, but no script is executed.
The source is:
var mst_width = "96%";
var mst_height = "350vh";
var mst_border = "0";
var mst_map_style = "simple";
var mst_mmsi = "244770624";
var mst_show_track = "true";
var mst_show_info = "true";
var mst_fleet = "";
var mst_lat = "";
var mst_lng = "";
var mst_zoom = "";
var mst_show_names = "0";
var mst_scroll_wheel = "true";
var mst_show_menu = "true";
window.onload = function () {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("head")[0].appendChild(element);
}
In the page source I see:
var mst_width = "96%";
var mst_height = "350vh";
var mst_border = "0";
var mst_map_style = "simple";
var mst_mmsi = "244770624";
var mst_show_track = "true";
var mst_show_info = "true";
var mst_fleet = "";
var mst_lat = "";
var mst_lng = "";
var mst_zoom = "";
var mst_show_names = "0";
var mst_scroll_wheel = "true";
var mst_show_menu = "true";
window.onload = function () {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("head")[0].appendChild(element);
}
Can someone please point me in the direction on how to get the script executed? I also assumed that the script should be appended to the 'body' instead of the 'head'm but I'm not sure about it.
Thanks!
Edit based change of head to body:
<script>
var mst_width="96%";var mst_height="350vh";var mst_border="0";var mst_map_style="simple";var mst_mmsi="244770624";var mst_show_track="true";var mst_show_info="true";var mst_fleet="";var mst_lat="";var mst_lng="";var mst_zoom="";var mst_show_names="0";var mst_scroll_wheel="true";var mst_show_menu="true";
window.onload = function() {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("body")[0].appendChild(element );
}
</script>
So, finally I managed to solve the problem and got the desired map in my browser... using the following HTML+JS code (which you can run with the button below):
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
<script>
var mst_width="100%";var mst_height="450px";var mst_border="0";var mst_map_style="terrain";var mst_mmsi="";var mst_show_track="";var mst_show_info="";var mst_fleet="";var mst_lat="";var mst_lng="";var mst_zoom="";var mst_show_names="0";var mst_scroll_wheel="true";var mst_show_menu="true";
function loadMap() {
var element = document.createElement("script");
element.setAttribute("id", "myshiptrackingscript");
element.setAttribute("async", "");
element.setAttribute("defer", "");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementById("mapContent").appendChild(element );
}
window.onload = loadMap
console.log('Registered onload')
</script>
</head><body>
<div id="mapContent" />
</body></html>
Two points of attention:
you should add the created script tag as child of a tag belonging to the body ot the page (I used <div id="mapContent"/> and getElementById to access it)
you should load the HTML page through a http:// URL, not through a a file:// one: with the latter you get an error with message like "Browser does not support embedded objects"
I hope this can help you to solve the problem in you real case!
There are many ways to invoke your function when the page has loaded.
My vanilla's js tool of choice most of the time is:
window.addEventListener('DOMContentLoaded', function(){
//your bindings and functions
}
That way of proceeding is preferred to your onload method as otherwise, you won't be able to attach multiple events when the DOM loads completely.
Try this:
window.onload=function(){
document.write('<script src="http://www.myshiptracking.com/js/widgetApi.js>
</script>');
}
wrap your javascript code with this:
if(document.readyState === 'complete') {
// good to go! Put your code here.}

What code is required to swap a javascript variable (trailimage) to another when clicking within a website

When clicking (onmousedown or onclick) for example, I would like to change the variable of the trailimge in the javascript to another image. You see, I have an image (a hand) that is following the cursor coordinates. I am unable to code and change the current image to swap to another trailimage after clicking. I will also need to find a way of reverting to the original trailimage when unclicking. The affect will seem as though the handis tapping or pointing.
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
I believe the answer may be within some form of swap variable scripting
e.g.
var a = 1,
b = 2;
var foo = 1;
var bar = 2;
foo = [bar, bar = foo][0];
Trailimage javascript excerpts
var trailimage=["images/contact/gardening-glove-cursor.png", , ]
var offsetfrommouse=[-110,5]
var displayduration=0
if (document.getElementById || document.all)
document.write('<div id="trailimageid" style="position:absolute;visibility:visible;left:0px;top:100px;width:1px;height:1px"><img border="0" src="'+trailimage[0]+'"></div>')
function followmouse(e){
var xcoord=offsetfrommouse[0]
var ycoord=offsetfrommouse[1]
if (typeof e != "undefined"){
xcoord+=e.pageX
ycoord+=e.pageY
}
</script>
Try this
Fiddle
var trailimage = ["http://img2.wikia.nocookie.net/__cb20130626213446/elderscrolls/images/2/2d/TES3_Morrowind_-_Glove_-_Black_Left_Glove.png",
"http://img2.wikia.nocookie.net/__cb20130626213454/elderscrolls/images/9/91/TES3_Morrowind_-_Glove_-_Black_Right_Glove.png"]
$(function() {
$(".logo").attr("src",trailimage[0]);
$(document).mousemove(function(e) {
$('.logo').offset({
left: e.pageX,
top: e.pageY + 20
});
});
$(document).on("mousedown",function() {
$(".logo").attr("src",trailimage[1]);
})
$(document).on("mouseup",function() {
$(".logo").attr("src",trailimage[0]);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logo" src="//ssl.gstatic.com/images/logos/google_logo_41.png" alt="glove" />
Possible Duplicate How do I change the style of the cursor with JQuery?
you can specify like
$('#trailimageid').css('cursor', 'url(' + trailimage[i] + ')');
assuming i as array index

Changing multiple images source using jquery (and some other thing as well)

I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};

Javascript method "undefined" when it is already?

I have the following code:
<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function googleJS1(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('div');
newScript.setAttribute("id", "google_translate_element");
var bodyClass = doc.getElementsByTagName('body')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[0]);
}
function googleJS2(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('script');
newScript.setAttribute("src", "http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[0]);
}
function googleJS3(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('script');
newScript.setAttribute("src", "http://www.mydomain.com/google.js");
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[1]);
}
function googleJS4(){
var iframe = document.getElementsByTagName('iframe')[0];
var doc = iframe.contentWindow.document;
var newScript = doc.createElement('style');
var content = doc.createTextNode('.goog-te-banner-frame { display: none; } #google_translate_element {}');
newScript.appendChild(content);
var bodyClass = doc.getElementsByTagName('head')[0];
bodyClass.insertBefore(newScript, bodyClass.childNodes[2]);
}
</script>
<iframe width=100% height= 100% onload ="googleJS1(); googleJS2(); googleJS3(); googleJS4();" class=iframe2 src="www.mydomain.com/test.html">
This code works fine on another server of mine elsewhere. However whenever this is run the console says "Uncaught referencer error, method undefined". Even though it is defined, why does it throw this message and how do I solve it?
Thanks
I haven't tested, but I'm assuming this is because the onload event is attached to the iframe, and will therefore be called inside the iframe's scope. Try calling window.parent.googleJS1() instead.

Categories