I've got a little bit of javascript embedded in my html (using a .aspx file). I want to perform some sort of if statement which then determines whether or not some sort of chart is displayed. This chart is displayed using html, and I'm assuming the if statement should be written in javascript. However, I don't really know how to "run" this html code from within java. It is basically just drawing a table. Any suggestions? I've seen document.write, but I've only seen that being used with single lines.
You don't really "run" an HTML code. HTML is a markup language and it is mostly used to format and arrange elements that are displayed in the web browser.
The problem you are probably trying to solve is: Display or hide an element based on some condition. A JavaScript code like this is what you want.
if (condition) {
document.getElementById('chart').style.display = "none"
} else {
document.getElementById('chart').style.display = ""
}
Of course whatever element is responsible for displaying the chart should have an id="chart" attribute. e.g. <div id="chart"><!-- Chart related code goes here --></div>.
The JavaScript code I have given alters the display CSS property of this element to hide it or make it visible.
In case this is not what you want but you want to dynamically modify the HTML responsible for the chart, then you need to use the innerHTML property of the element.
Example:
if (condition) {
document.getElementById('chart').innerHTML = "<!-- HTML Code for the chart here -->"
} else {
document.getElementById('chart').innerHTML = ""
}
I'm assuming the if statement should be written in javascript
Unless you are testing something that you can only find out out in JS, then do it server side in your ASP.NET code.
I don't really know how to "run" this html code from within
This is covered by chapter 47 of Opera's WSC: Creating and modifying HTML. You may wish to read some of the earlier chapters first.
java
Java has about as much in common with JavaScript as Car does with Carpet. They are completely different programming languages.
Try writing the if statement in javascript and then rendering the html with the JQuery html() function. Just use a custom html id to locate where you want the html code to go.
<div id = "custom-tag"> </div>
<script>
if (true){
$('#custom-tag').html('YourHtmlString');
} else {
$('#custom-tag').html('DifferentHtmlString');
}
</script>
Read more about html() here: http://api.jquery.com/html/
YourHtmlString & DifferentHtmlString is where you should store your custom html in string format. It will then be rendered wherever you included "div id = 'custom-id'
Hope this helps!
Related
html2pdf.js is a package for generating pdf's from html it is based on jspdf and html2canvas. It has a nice feature where it can insert page-breaks in order not to split elements. The way it works is that it loops over all the elements and creates empty div's where a page break needs to be inserted. I would like to style those divs and instead of having blank white space would like to be able to insert a class to determine how they would look. The issue is I don't seem to have access to this new HTML that will be converted to a pdf. The API seems to indicate that this is possible here but when I put in code like this:
var worker = html2pdf();
worker.set(opt).from(finalHtml).toContainer().toCanvas().then(newHtml => {
console.log(newHtml)
return newHtml
})
I am getting undefined. This is true whether I chain to toCanvas() and toContainer or not. Basically I would like the html generated here, how do I access this?
I want to make sure that all JavaScript happens before the page is loaded. I am changing some innerhtml, but don't want the original innerhtml to show.
Currently, when my page loads "Books" is displayed for a brief moment, then finally when the script is read, it gets replaced. How do I prevent it from displaying the initial text?
FYI the script exists inside a php file.
<?php
?>
<script>
function changeme(){
var myvar = "test-string-is-long-to-notice-the-changed-text";
var spans = document.getElementsByTagName("span");
for(var i=0;i<spans.length; i++) {
if(spans[i].textContent.trim().toLowerCase()==="books") { //is this the "Welcome" span?
spans[i].innerHTML = myvar; //change to new value
break; //hop out of the loop, we're done
}
}
}
window.onload = function() {
changeme();
};
</script>
It is not a good idea to load JS before HTML, because you can not change the HTML elements before loading it using js.
Solution 1: Initially, keep the html tags empty that you do not want to show, because you want to show new data from JS.
Solution 2: Initially, keep the styles for those elements "display: none" and when you add the data using Js in element. Update the style to display: 'block' or any other you want, eg spans[i].style.display = 'block';.
You cant apply JS to a html document that doesnt yet exist. Your html is always loaded first, then your JS is applied. What you could be seeing here is the html is loaded and the JS is taking like what--a second to load and make the change? I recommend figuring out a more efficient way to implement the JS you need. You could just be seeing JS latency. You could use a more efficient implementation plus some CSS to fix it. I could be wrong here but it just doesn't make sense to apply JS to html went the html isnt even there yet.
How would I apply any JS to that if I'm trying to do it before the browser has even parsed and rendered my html?
Also remember that PHP is always "loaded" first, then html, then JS
This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:
$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');
Is it possible to convert this to a readable format, for example using multi-lines. I tried
$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')
This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.
If you have to add the HTML inline style I would suggest the following format.
var html =
'<div class="somediv">\
<div class="otherdiv">\
.
..
...
</div>\
</div>';
$('#somediv').append(html);
You can do it this way -
$('#someDiv').append($('<div>').append($('<span>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
.append($('<div>'))
)
You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)
$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")
My solution would be to create all these elements
div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);
container.append(..)
This means a lot of code but you can outsource it, can easily change attributes and its good readable...
I'm fairly new to the whole JQuery/javascript world, but I've managed to wack together a working jqgrid with a datepicker & custom control (used jquery auto complete) based on code samples i found on the net. I've added the code to a T4 template in my project as it'll probably act as a base/starting point for most pages. (Side note. I'm using asp.net MVC)
JFIDDLE: LINK
1.) I'd like to move the initDateEdit & initDateSearch to the same function (using a parameter, to disable/enable the showOn property) as they are basically similar.
2.) How would be the best way to set nonWorkingDates from outside the new function/file. same applies to the autocomplete_element (I'd like to specify the url)
Changing
"function nonWorkingDates(date)" to => "function nonWorkingDates(date, nonWorkingDates)"
isn't working, (guess it's got got something to do with how its gets called "beforeShowDay: nonWorkingDates")
Thanks in advance!
If you have a chunk of JS code like this:
<script type="text/javascript">
... code goes here ...
</script>
You simply copy the whole thing, eliminate the containing script tags, and save the raw code
... code goes here ...
to a file, which you then include with:
<script type="text/javascript" src="yourfile.js"></script>
However, since you're using jquery, you'll have to make sure that this above snippet is placed AFTER the script tag that loads up jquery, or you'll get a "no such function" syntax error.
We've got a little tool that I built where you can edit a jQuery template in one field and JSON data in another and then hit a button to see the results immediately within the browser.
I really need to expand this though so the designer can edit a full CSS stylesheet within another field and when we render the template, it will have the CSS applied to it. The idea being that once we've got good results we can take the contents of these three fields, put them in files and use them in our project.
I found the jQuery.cssRule plugin but it looks like it's basically abandoned (all the links go nowhere and there's been no development in three years). Is there something better or is it the only game in town?
Note: We're looking for something where someone types traditional CSS stylesheet data in here and that is used immediately for rendering within the page and that can be edited and changed at will with the old rules going away and new ones used in their stead. I'm not looking for something where the designer has to learn jQuery syntax and enter in individual .css("attribute", "value") type calls to jQuery.
Sure, just append a style tag to the head:
$("head").append("<style>p { color: blue; }</style>");
See it in action here.
You can replace the text in a dynamically added style tag using something like this:
$("head").append("<style id='dynamicStylesheet'></style>");
$("#dynamicStylesheet").text(newStyleTextGoesHere);
See this in action here.
The cleanest way to achieve this is by sandboxing your user-generated content into an <iframe>. This way, changes to the CSS won't affect the editor. (For example, input { display:none; } can't break your page.)
Just render out your HTML (including the CSS in the document's <head>, and write it into the <iframe>.
Example:
<iframe id="preview" src="about:blank">
var i = $('#preview')[0];
var doc = i.contentWindow || i.contentDocument;
if (doc.document) doc = doc.document;
doc.open('text/html',true);
doc.write('<!DOCTYPE html><html>...</html>');
doc.close();
If the user should be able to edit a whole stylesheet, not only single style attributes, then you can store the entered stylesheet in a temporary file and load it into your html document using
$('head').append('<link rel="stylesheet" href="temp.css" type="text/css" />');
sounds like you want to write an interpreter for the css? if it is entered by hand in text, then using it later would be as simple as copy and pasting it into a css file.
so if you have a textarea on your page to type in css and want to apply those rules when you press the button, you could use something like this (only pseudocode, needs work):
//for each css id in the text area
$.each($('textarea[name=cssTextArea]').html().split('#'), function({
//now get each property
$.each($(this).split(';'), function(){
$(elem).css({property:value});
});
});
then you could write something to go through each element that your designer typed in, and get the current css rules for it (including those that you applied using some code like the snippet above) and create a css string from that which could then be output or saved in a db. It's a pain and much faffing around with substrings but unfortunately I don't know of a faster or more efficient way.
Hope this atleast gives you some ideas