Add html in jquery with differents contents - javascript

I have this little script for add differents parts of code to the body in website
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
WincontentBody=jQuery("</div>");
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
I try to add code from WincontentBody to body but it doesn't work, some kind of error i have in syntax, because never show div
I think this it's fine but I can't find the problem, the idea it's to add all contents from the variable WincontentBody to the body
Is it possible to do this? Because i can't make it to work
ThankĀ“s in advanced

I went ahead and wrote your question properly for you. Take a look at SO in Spanish.
fadeIn and appendTo are jQuery methods. WincontentBody contains a string. You should first create a new jQuery object with your html.
$(WincontentBody).appendTo('body').fadeIn(3000); //first append, then fade in
If the fadeIn doesn't seem to work, it's probably because you will have to hide the elements (with some css) before inserting them into the page. Otherwise you'll be trying to fade in something that's already visible.
And I don't know if your code is actually formatted like that or it just got wrapped here, but you can't have multiline strings, unless you end each line with \.
Now (after your edit), you are creating two jQuery objects. One with the div and the other with nothing valid.
WincontentBody=jQuery("<div class='wd_"+idw+"'id='win_container'>OK</div>");
//WincontentBody now has the div
WincontentBody=jQuery("</div>");
//WincontentBody now has nothing. The </div> is not being appended to what was in WincontentBody before, you're assigning a new value to it
jQuery(WincontentBody).fadeIn(3000).appendTo('body');
//You're appending WincontentBody (which has nothing valid) to the body
//Also, WincontentBody is already a jQuery instance, no need to call jQuery() again
What you should do is to create your WincontentBody with the html code, as you had before, and then use $(WincontentBody)... or jQuery(WincontentBody).... Or put the whole html code in a single jQuery element like:
var WincontentBody=jQuery("----all the html code at once----");
WincontentBody.appendTo("body").fadeIn(3000);

Try this.
$(document).ready(function() {
WincontentBody = "<div class='wd_asdfas'id='win_container'>OK This is fine.</div>";
$('.displayHere').append(WincontentBody);
$('.displayHere').fadeIn(3000);
});
body { background: #eee }
.displayHere { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<div class="displayHere">
Hello Buddy
</div>
</body>
Updated
I had made few changes.
I add the div named displayHere. I don't think it is good idea to
give the fade effect to body of the webpage.
In jquery I split the functions to two different functions. Firstly it will update the details and then it will fade in.

Related

JavaScript DIV Editing Destroys Functionality of Other Elements

So my website is built using a company's software called Inksoft which leaves me very little to work in the way of customization. So I have to do many workarounds.
Here is my site's homepage.
The header on top of the page only has two links right now. "Products" and "Design Studio". My goal is to add an "About Us" link and "Buyers Guide" to the header as well.
I cannot add new content to the header using Inksoft's backend. So I coded a workaround to replace the content of existing DIV's within the header to say and link to where I want them to go.
The only issue is, the responsive mobile-nav loses functionality when this is implemented. As seen here on this test page.
The test page has the About Us in the top header, added by the use of this code:
<script>
$("#header-nav-designs").html('<document.write="<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
So, the simplified question is: how do I implement this code without losing the responsive functionality of the nav bar?
The jQuery .html function will replace the HTML inside the target element. If you want to just append the one value, you likely want to .append to the element.
In addition, you aren't setting the HTML to a valid html string. You probably just want to get rid of the <document.write=" at the beginning of the string. The rest of it looks fine with just a cursory glance.
So:
<script>
$("#header-nav-designs").append('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
Edit:
After looking at it a little more, it appears as though the $('#header-nav-designs') that you are selecting is already an <li> which means you need to either select the parent <ul> list or you can use the jquery .after function instead.
<script>
$("#header-nav-designs").after('<li id="header-nav-studio"><font color="#000000">About Us</font></li>');
</script>
And as someone else commented above, you are getting an error on the page. It appears as though you are trying to get an element with the id divID and the appending some html to it, but there is no element with the id divID and so you are getting an error saying that you can't read the property innerHTML of null as the call to document.getElementById is returning null (element not found).
Element id header-nav-designs witch your code is referring have CSS style on line 170:
#header-nav-designs {display:none;}
The element will be hidden, and the page will be displayed as if the element is not there. With display:none;
If I understand you correctly your code selector points to wrong element id. It should point $(".header-nav > ul"). Document.write is not needed inside jQuery you need to give only an valid html string as argument.
jQuery html function erase html that is all ready inside element and replace it with html string given as argument. You have to use append if you want to add more html but not remove what is allready in element.
$(".header-nav > ul").append('<li><font color="#000000">About Us</font></li>');
$(".header-nav > ul").append('<li><font color="#000000">Buyers Guide</font></li>');

jQuery: fadeOut() with html(), weird behaviour

while making a simple random quote machine (part of a coding course I'm attending), I ran into a problem while trying to fade out an element in my HTML, that should then add some new HTML in it and fade it in. Here's the code:
$(".quote-text").fadeOut(function() {
$(this).html("<p>" + quotes[currentQuoteNum] + "</p>").fadeIn();
});
The quotes[currentQuoteNum] just refers to a list of quote strings I have. For some reason, neither the fadeIn or fadeOut functions do not animate correctly. The delay is there before my HTML is updated with a new quote, but the animation is not displayed. Now, if I remove the p element like so:
$(".quote-text").fadeOut(function() {
$(this).html(quotes[currentQuoteNum]).fadeIn();
});
Then it works and both the fadeIn and fadeOut animations are played. I need to have the p element in there, because inside them I'm adding another two elements to create quotation marks around my quote using a special styling class. I omitted those for simplicity. I know there are other ways but I want to know why this is happening.
Obviously this has something to do with adding tags to my HTML, but I have not been able to find out what it is. Please explain?
Code looks fine to me, should not be an issue.
Here is a codepen and it works as it should
Fade codepen
$(".quote-text").fadeOut(function() {
$(this).html("<p>" + "Oh Good"+ "</p>").fadeIn();
});
why not check the content of your variable.Probably its not well formatted
Try this change
$(".quote-text").fadeOut(2000, function() {
$(this).text(quotes[currentQuoteNum]).fadeIn(2000);
});
I just removed the inner <p> tag and replaced html() with text()
Here's working code pen http://codepen.io/anon/pen/wMgWvR

Issue in making appear the div in the foreach loop

Here is my Fiddle
Where i have
<div id="mulitplefileuploader" class="fileuploader">Upload</div>
<div id="status"></div>
in the html. In the Body i have the script that was in the fiddle and i have $(".fileuploader").uploadFile(settings); in the document.ready. All this will have only on file upload div,
If i am using a for loop say 5 times. It is not working I mean the div itself not appearing. As the for loop may have any count i can run the div in the for loop. But I should not have the same script in my html page (Because of few restrictions).
What shall i do to achieve my result. Allowing multiple div according to the html.
I tried here in this fiddle but it didn't succeed. How can i do this.
Note : All the upload should work, the js don't know how many loop will appear in the html
Update To run the code Here is the chop and you shall try it here in the display at html mode.
#reply to your comment: alright i see. If you take a look into the source code of the plugin, it has the missing .each to iterate all the retrieved selectors. so you can simply add one for it
$(".fileuploader").each(function(){ $(this).uploadFile(settings); });
http://jsfiddle.net/L08p1upt/4/

reccommended way to output HTML from JavaScript

I know this has probably been asked before, but here goes: I have a web application that needs to generate modal dialogs. alert, confirm, and prompt are too simple and ugly, and that modal window function...it's a long story. I can't use it. So, I'm going to create the modal box using DOM functions and CSS. However, I need to put quite a lot of content into the dialog, and I'm wondering what the best way to do this is. Putting the HTML into a string and using innerHTML is unwieldy. I could use the DOM, but that's annoying and takes too much time to code. I know I can use a script with a weird type tag (something like x-random/x-htmlstuff) and then copy it's content to the innerHTML, but is there a better, more "official" way to do this?
if the layout of the modals are static, just put them into the HTML of the page. Use CSS to set them to display: none when the page is displayed normally. When you want to display the model, use
document.getElementById('modal-id').style.display = 'block';
I've heard that some people use this solution:
<script type="text/html" id="popup_html">
html...
</script>
(of course, you should make it invisible)
But, most likely, if you're trying to write a lot of HTML from javascript, then you should retrace and think if there's a better way.
If you're using the same div multiple times, you should just create it in the HTML page, and display it when needed
if you're creating a new element - see if you can use the document.createElement and appendChild methods (assuming there aren't many nodes involved)
if neither apply - retrace. For large projects, maybe object-oriented javascript can help.
There's no magical way that I'm aware of. I usually just use innerHTML and write the HTML out in a well formatting from such as:
box.innerHTML = "<div id='boxChild'>\n" +
" <p>Put whatever content here</p>\n" +
"</div>";
The \n make it so if you view your code, it will be well formatted, and no one long string once the JS writes it.
A way to do this, is to generate the popups within the html and show or hide them when you need, like this:
<div class="myPopup">
<div class="pop-message msg-01">This a pre generated alert with the id: <span class="dynamic-field-01"></span></div>
<div class="pop-message msg-02">This another pre generated alert with the id: <span class="dynamic-field-02"></span></div>
<div class="pop-message msg-03">...</div>
</div>
.pop-message {
display: none;
}
Now while user navigates the page, you are going to hide and show the .pop-message's while replacing those .dynamic-field's if needed.
I would suggest having the HTML for your modal content in separate files, and then loading it asynchronously when you need it to popup the modal.
partials/modal.html
<div class="content">My modal content</div>
main.js
var modalContent = null;
function _fillModal() {
modal.innerHTML = modalContent; // something like this
}
function openModal() {
if (!modalContent) {
// XMLHttpRequest, which populates the modalContent variable
// and in the callback, calls _fillModal()
}
// If already filled, just call
_fillModal()
}
If you want the content to be dynamic, make modal.html a template, and use a JS template library (for example http://underscorejs.org/#template), or write a simple RegExp replace yourself.
I'd suggest loading it with innerHTML or using jQuery to simplify things, but if you need
a modal window, could you use the jQuery UI modal dialog, shown here?
If you have the content loaded in divs in your HTML, and have them have css display:none;, and then show them with
document.getElementById("unshown-div").style.display="block";
If you can use jQuery, a modal box could be done with
<div id="modal" style="display:hidden">
Here is a modal dialog bbox
</div>
and your script:
$("#dialog").dialog();
Whatever you do, just don't use document.write()

Create new (not change) stylesheets using jQuery

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

Categories