Set 'src' attribute for document.createElement('script')? - javascript

I'm trying to create a highchart on a different tab. But Im getting error that high chart is not defined. I have tried to register Highchart.js using different methods. Code is given below.
function OpenWin() {
var w = window.open();
w.document.open();
w.document.write('<div id="container" style="width:100%; height:400px;"></div>');
var scriptHead = w.document.createElement("SCRIPT");
//scriptHead.setAttribute('src','http://code.highcharts.com/highcharts.js');
var link = "http://code.highcharts.com/highcharts.js";
scriptHead.src = link;
w.document.head.appendChild(scriptHead);
var script = w.document.createElement("SCRIPT");
w.document.body.appendChild(script);
var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); console.log(JSON.parse(a)); var chart = new Highcharts.Chart(JSON.parse(a))');
script.appendChild(js);
w.document.close();
}

You need to wait for previous script to load. Demo.
function OpenWin() {
var w = window.open();
w.document.open();
w.document.write('<div id="container" style="width:100%; height:400px;"></div>');
var scriptHead = w.document.createElement("SCRIPT");
//scriptHead.setAttribute('src','http://code.highcharts.com/highcharts.js');
var link = "http://code.highcharts.com/highcharts.js";
// bind on script load event
scriptHead.onload = function() {
var script = w.document.createElement("SCRIPT");
w.document.body.appendChild(script);
var js = w.document.createTextNode('var a = localStorage.getItem("ImportOptions"); console.log(JSON.parse(a)); var chart = new Highcharts.Chart(JSON.parse(a))');
script.appendChild(js);
w.document.close();
}
// as A.Wolff mentioned you might need to set onload befor src for some browsers.
scriptHead.src = link;
w.document.head.appendChild(scriptHead);
}

Related

Javascript functions do not work after updating content (Using Document Ready atm.)

I have a question I am working with a form based shopping cart add function and a livesearch (PHP) function where it requests new data with the same classes. I have seen multiple examples besides (document.ready) but none of them seemed to work correctly after the DOM Content has been modified by the PHP livesearch function. (The current method is on the document ready function as you guys can see.
Thanks in advance!
// Icon Click Focus
$('.product').on('click', function() {
var strId = '';
var strId = $(this).attr('class');
var strId2 = strId.replace(' product','');
var strId3 = strId2.replace('product-','');
var formData = "product"+strId3;
document.getElementById("product_toevoeg_id").value = strId3;
var productNaam = $("#"+formData+" .f-productnaam").val();
document.getElementById("productnaam").innerHTML = productNaam;
document.getElementById("product_naam_form").value = productNaam;
var productIngredienten = $("#"+formData+" .f-ingredienten").val();
document.getElementById("ingredienten").innerHTML = productIngredienten;
document.getElementById("ingredienten_form").value = productIngredienten;

Pass value to be inserted in div to open window

I am trying to open a new window in the same tab and pass some html code to be inserted in a div section of the new open window. I am having trouble to pass the data as shown below:
Parent javascript:
function popupPlace() {
var mywindow = window.open('Details.html','_self');
mywindow.dataFromParent = placeListAll;
mywindow.init();
}
Child javascript:
<script type="text/javascript">
var dataFromParent;
function init() {
document.getElementById('Place').innerHTML=dataFromParent;
}
</script>
The init method is not being called.
Are you sure you're not talking about a new tab in the same window? Anymway the better way for you to send data in your new tab seems to pass it as url param :
window.open('Details.html?data=some-data-maybe-b64-encoded','_self');
Then you can get it in child with :
var urlParams = new URLSearchParams(window.location.search);
var data = urlParams.get('data'));
finally :
//parent
function popupPlace() {
//encoding to be able to store html in uri
var htmlForChild = encodeURIComponent("<p>Content for Children</p>");
var mywindow = window.open('Details.html?data=' + htmlForchild, '_self');
mywindow.dataFromParent = placeListAll;
mywindow.init();
}
//child
function init() {
var urlParams = new URLSearchParams(window.location.search);
document.getElementById('Place').innerHTML=decodeURIComponent(urlParams);
}

JavaScript, move an image on another

I want to move an image on another one. I saw on forum, the best way to do this is to use destination.appendChild(elementToMove). But when I use it, my elementToMove just disappears.
Here is a fiddle for what I want to do (but that's not working):
JS Fiddle
Here is my JS Code:
var body = document.getElementsByTagName("body")[0];
var td_sign = document.getElementById("sign");
var td_moon = document.getElementById("moon");
var sign = document.createElement("img");
sign.src="http://img11.hostingpics.net/thumbs/mini_723286sign.png";
var moon = document.createElement("img");
moon.src="http://img11.hostingpics.net/thumbs/mini_418048moon.png";
td_sign.appendChild(sign);
td_moon.appendChild(moon);
var testbutton = document.createElement('input');
testbutton.type='button';
testbutton.value='test';
testbutton.onclick = function(){
sign.appendChild(moon);
}
body.appendChild(testbutton);
I just want to use JavaScript.

Change pixels on canvas. It does not work

Code JavaScript
var imgWidth,imgHeight,datosPrint;
window.onload = function(){
/*canvas,ctx,img...*/
ctx.drawImage(img,0,0,imgWidth,imgHeight);
var datosDeLaImagen = ctx.getImageData(0,0,imgWidth,imgHeight);
datosPrint = datosDeLaImagen.data;
invertirColores(canvas,ctx);
};
ctx.getImageData is not work. Why?
You dont just manipulate the data object and see the changes, you have to put the manipulations back into the context when your done.
var imgWidth,imgHeight,datosPrint;
window.onload = function(){
/*canvas,ctx,img...*/
ctx.drawImage(img,0,0,imgWidth,imgHeight);
var datosDeLaImagen = ctx.getImageData(0,0,imgWidth,imgHeight);
datosPrint = datosDeLaImagen.data;
invertirColores(canvas,ctx);
ctx.putImageData(datosPrint, 0, 0)
};
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData

getElementById() within $(document).ready() returns null

I am "new" to JavaScript, making my first image- and media-slider for a website.
I have searched for answers in the web and here in SO, but they did not work for me.
My last big change was to divide my script into two parts. One outside of $(document).ready() and one inside. I want the user to be able to call a function via a button in the HTML. To make this possible this function has to be global and can not be located inside the $(document).ready(). Am I right?
Before I divided my script everything was inside the $(document).ready() area and it worked properly. But of cause I could not call the function via a button.
But now the part inside my $(document).ready(), which has to build the slider when the page is loaded, is not waiting for it. All my getElementById()'s are producing the error: "Can't set property 'style' of null." So the slider will not be built.
This is telling me getElementById() returns "null" even if it is inside $(document).ready().
HTML:
<!-- very content -->
<link href="...css" />
<script src="...js" />
<div id="slider"></div>
<!-- more content -->
<div id="changeContent"></div>
<!-- more content -->
</body>
</html>
JavaScript:
// Configuration
var slidersParentId = 'imslider';
var slideShowTitle = '';
var thumbnailWidth = 20;
var slidesWidth = 281.25;
var slidesHeight = 144.5625;
var currentSlideWidth = 500;
var currentSlideHeight = 257;
var nextSlideWidth = 375;
var nextSlideHeight = 192.75;
var prevSlideWidth = nextSlideWidth;
var prevSlideHeight = nextSlideHeight;
var resizeDifference = currentSlideWidth - nextSlideWidth;
var slidesMargin = 20;
var animationDistance = slidesWidth + slidesMargin;
var animationSpeed = 2000;
var intervalSpeed = 7000;
var contentDiv = "descriptif_site_spip";
// Variables from slides.json
var numberOfSlides;
var jsonSlides = {};
var bgImgUrl;
// Cache the DOM
var $slideShow = $('#'+slidersParentId);
var $slideInner;
var $slides;
var $slideNav;
var $navThumb;
var $thumb;
var $hovers;
var $content = document.getElementById(contentDiv);
// Other global Variables
var interval;
var currentSlide = 1;
var nextSlide = currentSlide + 1;
var prevSlide = currentSlide - 1;
var lastSlide = currentSlide;
var lastCurrentDif;
var lastNextSlide = lastSlide + 1;
var lastPrevSlide = lastSlide - 1;
var thumbImgs = [];
var navTo;
var interval;
var i;
// Global Variables for dragging
var dragStartPosition;
var dragStopPosition;
var draggedDistance;
var slidesDragged;
var posSlidesDragged;
var negSlidesDragged;
// IRIS-MEDIA-MODUS ?!
var iris_mode = 1;
//global functions...
//global warming...
$(document).ready(function(){
$.ajax({}
//getting some json...
});
// Building the slideshow windows
if (slideShowTitle !== 0) {
$slideShow.append('<h2 class="slideShowTitle">'+slideShowTitle+'</h2>');
}
$slideShow.append('<div id="outerWindow"><div id="innerWindowPositioner"<div id="innerWindow"></div></div</div>');
$slideInner = $slideShow.find('#innerWindow');
$slideInner.css({'width': numberOfSlides*slidesWidth+numberOfSlides*slidesMargin*currentSlideWidth*3});
// Building the slides & hovers
for (i=1; i<=numberOfSlides; i++) {
var idSlides = "slide_Nr"+i;
alert(idSlides);
var idHover = "hover_Nr"+i;
var j = i-1;
bgImgUrl = "url('" +jsonSlides[j].mediaUrl+ "')";
var title = jsonSlides[j].title;
var artUrl = jsonSlides[j].articleUrl;
var subtitle = jsonSlides[j].subtitle;
var text = jsonSlides[j].text;
var date = jsonSlides[j].date;
$slideInner.append('<div class="slide" id="'+idSlides+'"><div class="hover" id="'+idHover+'"></div></div>');
$('#'+idSlides).css('top', '56.21875px');
document.getElementById(idSlides).style.backgroundImage = bgImgUrl;
$('#'+idHover).append('<div class="hover-title"><h3>'+title+'</h3><span class="hover-subtitle">'+subtitle+'</span></div><span class="hover-date">'+date+'</span><br clear="all" /><p class="hover-text">'+text+'</p>');
}
$slides = $slideInner.find('.slide');
$hovers = $slides.find('.hover');
// Building the thumbnail navigation
$slideShow.append('<div id="slideShowNavigation"><ul id="navigationThumbnails"></ul></div>');
$slideNav = $slideShow.find('#slideShowNavigation');
$navThumb = $slideNav.find('#navigationThumbnails');
for (i=0; i<numberOfSlides; i++) {
thumbImgs[i] = jsonSlides[i].mediaUrl;
// alert(thumbImgs);
}
for (i=1; i<=numberOfSlides; i++) {
j = i-1;
var idThumbs = "thumb_Nr"+i;
bgImgUrl = "url('" +jsonSlides[j].mediaUrl+ "')";
$navThumb.append('<li class="thumb" id="'+idThumbs+'"></li>');
document.getElementById(idThumbs).style.backgroundImage = bgImgUrl;
}
$thumb = $navThumb.find('.thumb');
$( '<li class="year"> > 2000 > </li>' ).insertBefore( "#thumb_Nr62" );
$navThumb.prepend('<li class="year">1980 >> </li>');
$navThumb.append('<li class="year"> 2020&nbsp>></li>');
$navThumb.append('<br clear="both" />');
// ...some
// ...more
// ...functions
});
With this HTML-structure it is not working.
When I put the script-inclusion at the end of my HTML it works correctly and the slider will be built.
So why is my $(document).ready() firing too early?
I also tried $(window).load() but it hat no effect.
Or is there any why to make function inside $(document).ready() globally available without removing it from $(document).ready()?
Probably because your script is running before the rest of the page loads. Try using $(window).ready().
EDIT:
Had wrong function .load() I meant to have .ready()... Whoops!
My last big change was to divide my script into two parts. One outside of $(document).ready() and one inside. I want the user to be able to call a function via a button in the HTML. To make this possible this function has to be global and can not be located inside the $(document).ready().
Actualy, it can:
All global JavaScript objects, functions, and variables automatically become members of the window object.
I suppose you need something like this:
window.addEventListener('DOMContentLoaded', function () {
window.my_magic_function = function (/* my magic params */) {
/* doing my magic */
};
});
<button onclick="my_magic_function(/* my magic params */)">Do magic</button>
window.addEventListener('DOMContentLoaded', ...) equivalent to $(document).ready(...)

Categories

Resources