I have a javascript code and i want to insert an image inside the dynamically created html page. Please correct me if i'm going wrong with the code. the code runs something like this:
var html = [
'<div class="uicomponent-panel-controls-container");">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
_dockPanel.container.append(html);
Thanks in advance.
You have a typo here: ...container");">'
Here is the working (for demo purpose slightly modified) fiddle:
var image1 = 'https://image.flaticon.com/teams/slug/freepik.jpg';
var html = [
'<div class="uicomponent-panel-controls-container">',
'<img src=' + image1 + '>',
'</div>'
].join('\n');
document.getElementById("dock").innerHTML = html;
<div id="dock"></div>
var html = [...].join('');
html rendering dom does not need to be separated by '\n'
Related
I have written a lightbox script in plain JS:
HTML:
<img onclick="pLightbox(this)" src="MyPhoto.jpg" />
JS:
function pLightbox(objPhoto){
var path=objPhoto.src;
HTMLtext = '<img src="' + path + '">';
containerDiv.innerHTML = HTMLtext;
}
(code abbreviated for clarity)
This works fine. Now I'm trying to access the next sibling within the DIV. I have tried:
HTMLtext += '<img src="images/Next.png" onclick="pLightbox(' + objPhoto.nextElementSibling + ')">';
This doesn't work - Tried several different variations (nextElementSibling.src, etc.) , but nothing works.
How do I access the next sibling from an HTML string?
Eh, no. Do not concatenate DOM elements with strings. Do not use event handlers. Especially, do not use event handler content attributes.
This is the proper way. No events in HTML. No nasty string manipulation. No HTML injection vulnerabilities.
document.querySelector('img').addEventListener('click', pLightbox);
function pLightbox() {
containerDiv.innerHTML = "";
var img = document.createElement('img');
img.src = this.src;
img.addEventListener('click', pLightbox.bind(this.nextElementSibling));
containerDiv.appendChild(img);
}
<img src="//stackoverflow.com/favicon.ico" />
<img src="//scifi.stackexchange.com/favicon.ico" />
<img src="//superuser.com/favicon.ico" />
<img src="//crossvalidated.com/favicon.ico" />
<div id="containerDiv">Click the first image. Then keep clicking the new image</div>
Whenever I add the code below as a widget to my blog, the slider (Welcome...) on it will stop working. The slider should scroll through a few different images. I've read that 'no.conflict' will fix this problem but for the life of me haven't a clue where to put the code.
Recent Videos Widget
<script src='http://code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<style type="text/css">
div.PBTytC {clear:both;padding:5px;font-size:12px;}
div.PBTytC.odd {background-color: #;}
div.PBTytC_thumb {position:relative;float:left;margin-right:8px;line-height:1;}
div.PBTytC_thumb img {width:76px;height:78px;border:0px solid #55A66B;}
div.PBTytC_title {font-weight:none;}
</style>
<script type='text/javascript'>
var PBTYoutubeUserName = "XXX";
var PBTYoutubeMAXResults = 3;
var PBTYoutubeAllow = "";
var PBTYoutubeDisallow = "";
var PBTYoutubeWgetIsEmpty = "No entries";
$(document).ready(function() {
$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=58c841d14337ba4fbf693abd9701dc49&_render=json&max-results="+PBTYoutubeMAXResults+"&allow="+PBTYoutubeAllow+"&disallow="+PBTYoutubeDisallow+"&user="+PBTYoutubeUserName+"&_callback=?", function(response) {
var htm = "";
for(var i=0;i<response.count;i++) {
var item = response.value.items[i];
htm += '<div class="PBTytC';
if(i%2 == 1) htm += ' odd';
htm += '"><div class="PBTytC_thumb"><a target="_blank" href="' + item.link + '"><img title="' + item.title + '" src="' + item.thumb + '"/></a></div>';
htm += '<div class="PBTytC_title"><a target="_blank" href="' + item.link + '">' + item.title + '</a></div>';
htm += '<div class="PBTytC_description">' + item.description + '</div><div style="clear:both;"></div></div>';
}
if(htm == "") htm = PBTYoutubeWgetIsEmpty;
$("#PBTytWdtLoad").html(htm);
});
});
</script>
<div id="PBTytWdtLoad">Loading...</div>
Here is the link to my blog: Link
Thanks for reading and hopefully helping me out.
Including JQuery twice can cause issues. The code fragment above and your blog both have a script tag for query. Try adding it to your blog without including JQuery again.
As for the plugin not working:
Your site includes JQuery; Then it has a lot of scripts that use JQuery; Then it has a script that changes the JQuery operator so that $ isn't use since this will cause conflicts with other scripts using the variable $ in another way. Considering the amount of scripts on your site I'm surprised you don't have more issues.
Anyway after your last script tag you can't use $ in your scripts you have to use jQuery instead. For example:
jQuery(document).ready(function() {
jQuery.getJSON("http://pipes.yahoo.com/pipes/pipe.run?
If you go through your whole script and change '$' to 'jQuery' then that will help with your script where it is in your page now, with the current page listed at your blog.
Really though, this is just putting a band-aid on a bigger problem. It's worth thinking about what scripts you really need.
buildIMG = (src, resize) ->
html = '<div class="left"><div class="foods_image">'
html += '<a onclick="popitup("http://somewhere.com/test" href="javascript:void(0)">'
html += ' <img src="'+src+'" '+resize+' />'
html += '</a>'
html += '</div></div>'
html
popitup = (url) ->
newwindow=window.open(url,'name','height=640,width=640')
newwindow.focus() if window.focus
false
I currently have a bookmarklet that inserts javascript code(the one above) into a website. I wrote the above coffeescript and it generates this:
(function() {
var buildIMG, popitup;
buildIMG = function(src, resize) {
var html, nbsp;
html = '<div class="left"><div class="foods_image">';
html += '<a onclick="popitup(\'http://somewhere.com/test\');" href="javascript:void(0)">';
html += ' <img src="' + src + '" ' + resize + ' />';
html += '</a>';
html += '</div></div>';
return html;
};
popitup = function(url) {
var newwindow;
newwindow = window.open(url, 'name', 'height=640,width=640');
return newwindow.focus()(window.focus ? false : void 0);
};
}).call(this);
I snipped the functions that uses buildIMG. That function creates an overlay over the site and displays all images in that overlay. buildIMG is called for each image to create the html.
The problem is that the onclick="popitup("http://somewhere.com/test" portion doesn't work. It is undefined.
A solution I did was to remove this which was generated by CoffeeScript:
(function() {
}).call(this);
It was fixed as soon as I removed that. How do I not have CoffeeScript put in those lines in my generated javascript?
CoffeeScript allows to compile JavaScript without this safety wrapper by --bare option.
Although suppressed within this documentation for clarity, all
CoffeeScript output is wrapped in an anonymous function: (function(){
... })(); This safety wrapper, combined with the automatic generation
of the var keyword, make it exceedingly difficult to pollute the
global namespace by accident.
It's from CoffeScript site.
If you want to create a global method or variable you need to
root = this
localProperty = "111"
root.property = localProperty
And then you'll get a property in global scope.
I am trying to use the google chart tools (from the visualization api; not the image charts) using an infoBubble. The infobubble is awesome; does exactly what I need it to. My project calls for using a chart in one of the tabs on the infobubble. So I am trying to use this code (see below) to build a contentString that will create a chart in the div's content. It isn't making any charts happen, though. Does anything look wrong, in particular, with the content string?
//returns the status string
function GetPublicProjectStatusString(data){
var contentString = '<div id="content" style="margin:0;">'+
'<h3>' + 'Project Phase' + '</h3>'+
'<p>' + data.ProjectPhase + '</p>'+
'<div id="parentDiv">' +
'<div id="chartDiv" style="top:0px;left:0px;width:200px;height:200px;">' +
'</div>' +
'<div id="secondDiv">' +
'<h3>' + 'Start Date' + '</h3>' +
'</div>' +
'</div>' +
'</div>' +
'<script type="text/javascript">' +
'var chartdata = new google.visualization.DataTable();' +
'chartdata.addColumn("string", "Source");' +
'chartdata.addColumn("number", "Amount");' +
'chartdata.addRows([' +
'["Federal",4],' +
'["State",8],' +
'["County",9],' +
'["Local",14],' +
']);' +
'var options = {"title":"Project Budget"' +
'"width":200,' +
'"height":200};' +
'var chart = new google.visualization.PieChart(document.getElementById("chartDiv"));' +
'chart.draw(data,options);' +
'</script>';
return contentString;
}
I think the following approach might be helpful to you as I dont think you can use the script tags in the content string.
Use a div in the content string where you want to place your graph
var contentString = "<div id='chart_div'></div>";
Have a look at this google chart example that can be adapted to add the chart to the div in the content string:
Google Charts Tools Example
However the div in your content string will probably be created by user input like clicking a marker so you cannot directly add the chart to it (which is done in the chart example) as it is not part of the dom yet. Therefor your have to listen to the event that creates the infoBubble. For a infowindow connected to a marker in the google maps api this will be something like this:
google.maps.event.addListener(infoWindow, 'domready', function() { drawChart(); });
Where infoWindow is the info window you created and drawChart a function you wrap the adapted chart code example in.
Hope this helps.
Failing to so call chart::draw() within the domready event handler appears to be what was causing the "... browser does not support Google Charts" error message I was seeing.
I have a javascript variable I need to create like this:
var HTMLContent = '<div class="className">HTML Content</div>';
How can I format it in an easier to read format because I'm going to want to create multiple lines of HTML.
e.g.
var HTMLContent = '
<div class="className">
HTML Content
</div>
';
Is something like that possible?
It would also be good if I could import via URL e.g. var HTMLContent = 'http://domain.com/page.html';
var longStr = "You can split\
the string onto multiple lines\
like so";
An example using your HTML would be:
var longStr =
'<div class="className">\
HTML Content\
</div>';
To load external HTML, check out jQuery's load method:
$('#result').load('ajax/test.html');
In your page markup, add a hidden template div, like:
<div id="contentTemplate" style="display: none;">
<div class="className">
HTML_CONTENT
</div>
</div>
...then in your JavaScript, you can do something like:
var newContent = 'The content for the new element';
var templateContent = document.getElementById("contentTemplate").innerHTML;
var htmlContent = templateContent.replace("HTML_CONTENT", newContent);
You could also use an AJAX request to pull the value of newContent from a URL to get your dynamic content loading working. If you plan on doing this, however, then I suggest you investigate using a framework like jQuery, which can greatly simplify this process.
You can also use backticks
function myFunc() {
var HTMLContent =`
<div class="className">
<div>HTML Content</div>
</div>
`;
document.getElementById('demo').innerHTML = (HTMLContent);
}
myFunc()
<div id="demo"></div>
var HTMLContent =
'<div class="className">' +
'HTML Content' +
'</div>';
You can do something like:
var HTMLContent = '<div class="ClassName">' +
'HTML Content' +
'</div>';
You can use escape characters:
var HTMLContent = '<div class="className">\n\tHTML Content\n</div>';
I may have misinterpretted the question, you want the javascript to be more readable, not the html stored in the variable?
var HTMLContent = "" +
"<div class=\"className\">\n" +
" HTML Content\n" +
"</div>\n" +
"";
This way, the script that writes it it pretty and the code it writes will be pretty too if someone were to view-source.