inline image insertion through javascript - javascript

I wrote one script which gets an image url through JSONP, and then I needed to write that to browser, this is a status image which is onling.png, offline.png and so on
my script looks like this.
<div id='STATUSDIV'></div>
<script language=javacsript type=text/javascript src=http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js></script>
<script type="text/javascript">$(document).ready(function()
{
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(),
function(res)
{
document.getElementById('STATUSDIV').innerHTML = ("<img src='"+res.img+"' />");
});
});
</script>
using this code, I am able to get an image inside div statusdiv, however I can not use same code block twice on single page as both will point to same div.
quick thing I can do is that I can ask end user who will copy this code multiple time on each page to change div id so that that image will load on differnt div.
But I wanted to have same code wherever copied just writes image inline. kind of createelement and write in that element. but thats not working. document.write does not work either as it replaces everything.
Is there a way that when this code block called, Instead of writing innerhtml, code creates a dynamic div right there on the page and writes image in that. and this image writing and creating div happens where script block is called. so that If same script is called in header and footer, status image will appear on both header and footer.

The cleanest way I know of is to create a function for your code that should get included very early in the page so it's available everywhere:
function insertStatusHere() {
var thisId = "status" + insertStatusHere.myDivCntr++;
document.write('<div class="statusContainer" id="' + thisId + '"></div>');
$(document).ready(function() {
$.getJSON('http://MYSSERVERNAME.COM/get.php?callback=?','q=value&index'+Math.random(), function(res) {
document.getElementById(thisId).innerHTML = ("<img src='"+res.img+"' />");
});
});
}
insertStatusHere.myDivCntr = 0;
Then, any place in the page where someone wants a status image, they can put this inline script:
<script type="text/javascript">
insertStatusHere();
</script>
This dynamically inserts a div with a unique div ID at the place that the function call is made and it keeps track of each ID that is used in the closure.

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

make more entire div clickable on wordpress using jQuery

SUMMARIZE THE PROBLEM
I state that I know practically nothing about html and javascript languages, I know the css. On wordpress, with visual composer, i was trying to make an entire row clickable. I've done it using a jQuery code founded online:
<script type="text/javascript">
jQuery(".LinkZoom1").click(function() {
window.location = "http://www.framedvision.org/portfolio/videomapping_oggetti_milano/";
});
</script>
I've added to the visual composer the object for java and I've put in the code. After I created the classes, inserted the link, added to the CSS the "cursor: pointer" function and everything works correctly.
THE PROBLEM IS THAT IT WORKS ONLY ON A SINGLE ROW. When I try to duplicate the code, assign different classes and links to create more clickable divs, it doesn't work. The result is that only the first div of the page is clickable, the divs are not.
WHAT I'VE TRIED
I tried the following codes in different combinations:
<script type="text/javascript">
jQuery(".class1”).click(function() {
window.location = “#1”;
});
</script>
<script type="text/javascript">
jQuery(".class2”).click(function() {
window.location = “#2”;
});
</script>
<script type="text/javascript">
jQuery(".class3”).click(function() {
window.location = “#3”;
});
</script>
<script type="text/javascript">
jQuery(".class4”).click(function() {
window.location = “#4”;
});
</script>
<script type="text/javascript">
jQuery(".class5”).click(function() {
window.location = “#5”;
});
</script>
Always using the object for java code: I put them all together, put individually in the row that I want to make clickable, it doesn't work. The result is always the same: only the first div becomes clickable. Even moving the object for java code away, from the first row to other rows, the result is the same. The first div is always the only clickable.
I found the solution. By importing the code written above, as corrected by you, it works. I don't know if this method is theorically correct, but it works fine. So...
In the visual composer, you have to insert an object to add the java code in each row that you want to make clickable (for example: for 5 clickable divs, you make 5 objects to insert the java code). Inside each object you have to insert the specific code for each class:
<script type="text/javascript">
jQuery(".class1”).click(function() {
window.location = “#1”;
});
</script>

Running Javascript inside Iframe without affecting the main page

I have to add an iframe in my webpage and inside that load a widget with the use of javascript.
I have done a lot of research on this and found that this implementation affects the main page as well probably because of the other css and scripts the widget might load.
So basically in a nutshell I have only one question-
What is the best way to make an iframe element and attatch a script to that so that it doesn't affect the whole page.
The different pieces of code I have used till now,
iframe=$('<iframe>');
iframe[0].appendChild('<scr' + 'ipt type="text/javascript" src="https://somecode.com/code/js-widget/orderingWidget.js"></scr' + 'ipt>');
Error:iframe[0] is undefined.
The other one
var previewDoc = window.frames[0].document;
previewDoc.write("<!DOCTYPE html>");
previewDoc.write("<html>");
previewDoc.write("<head>");
previewDoc.write("<style type='text/css'></style>");
previewDoc.write("<script type='text/javascript' src='https://somecode.com/code/js-widget/orderingWidget.js'");
previewDoc.write("</head>");
previewDoc.write("<body>");
previewDoc.write("test");
previewDoc.write("</body>");
previewDoc.write("</html>");
previewDoc.close();
Error: window.frames[0] is undefined.
And this one, where iframe is already created using jquery and assigned id=myiframe,
$(function() {
$iframe = $('#myiframe');
$iframe.ready(function() {
$iframe.contents().find("body").append('Test');
});
});
Error:Affects the whole page and triggered through console and not actually the function being called.
Thanks in advance.
PS:I have used content.document and content.window.document, both return undefined.

how do I target a specific id with ajax?

I'm trying ajax (and to a degree a lot of js) for the first time so I'm not sure what I'm doing wrong.
The goal is that a series of thumbnails in a sidebar will change the content of a centrally located div when selected. The link currently looks like this:
<img src="images/thumbs/elon-scissors-logo.jpg" onclick="reloadMiddleWith('about','about','test')"/>
When clicked it runs the below function and changes the background and calls a php source.
function reloadMiddleWith(theme, page, content) {
var new_url = "http://www.chrisjohndesigns.com/" + page + ".php/#" + content;
$('#live-area').addClass(theme);
$.ajax({
url: new_url,
dataType: 'html'
})
.done(function(data) {
// Assuming the request returns HTML, replace content
$('#area-loader').html(data);
});
}
I tested that and it worked fine when it was just the background and the new php page, but rather than making 50 pages to call in (and not even trying arrays or databases at the moment for lack of proper understanding) I thought I would just make 1 or 2 new page that repeat the same container style and just call the one I want to display by id tag. Currently when I try it, it just changes the background but does not change the php content.
The jQuery itself has a handy function jQuery(...).load, using it jQuery would handle all the necessary points:
function reloadMiddleWith(theme, page, content) {
var new_url = "http://www.chrisjohndesigns.com/" + page + ".php/#" + content;
$('#live-area').addClass(theme);
jQuery("#area-loader").load(new_url);
}
for more information check documentation page out.

reinitialize processing.js sketch after ajax request

I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.

Categories

Resources