I have a rails partial that renders this html:
<div class="content"></div>
<script>
// load the content here and get the adjacent div and populate it.
</script>
This partial template gets embedded in the main document by the server and also several times as response to AJAX requests. So the page has several instances of this partial.
Whenever my script executes I want only the div adjacent to the script to be affected.
So I am hoping if I could get to the script, I can get to the div. I use jQuery as well and I also use several async scripts (this prevents me from using the last executed script)
I could get to the adjacent div through document.currentScript , the problem is some browsers don't support it.
Then, is the only way to do is to create some sort of a UUID ID for the div and access it by Id from the DOM?
I really wished div supported onload, but sadly not.
You can create the element immediately after the <script> (document.write) and find the .content relative to it.
(function(){
var id = 'id' + (new Date().getTime());
document.write('<div id="'+id+'"></div>');
var elem = document.getElementById(id);
var content = elem.previousElementSibling.previousElementSibling;
content.innerHTML = 'NEW CONTENT';
})();
Example jsbin
If each partial belongs to an ActiveRecord model, use dom_id function available in Rails - in the div and in the corresponding script.
Use jQuery replaceWith:
<div id="div_id" class="content"></div>
<script>
# on document load
$('#div_id').replaceWith(new_content);
</script>
Related
Till now we are using Iframe to load HTML and script to show the form to the user.
Now, we want to move from Iframe to DIV, but here we have a problem with script.
Because Iframe is responsible to apply the loaded script to the only iframe, but coming to div script will be loaded into entire HTMLDocument.
Is There any way that loaded script can be applied to that specific DIV only?
Thanks.
First, change your <iframe></frame> to <div></div> after this, you have this way to do this for your CSS(to a certain div):
#projectName{
style:value;
}
#divAnnounce{
}
The # targets things with ID's if you use a . before it will target the class names,
You can also use both if you need to get specific such as
#idname.classname{
}
If you have another div inside of the divAnnounce you can do
#divAnnounce #yournewdiv{
}
OR
#divAnnounce div{
}
OR
#newdivid{
}
Notice the space inbetween the two targets saying that they are a parent and child.
For your javascript I don't know with you are using plain javascript or jQuery
if it is jQuery then you can use jQuery noconflict. Create separate aliases to use jQuery for example to div1 & div2
Simple Example:
<script>
var div1Alias = $.noConflict();
var div2Alias = div1Alias.noConflict();
jQuery(document).ready(function(){
alert(div1Alias( "#div1" ).html());
alert(div2Alias( "#div2" ).html());
});
</script>
Try to do this changes in your code and let me know if it helps :)
I've started using .NET Core to develop ASP sites and so I wanted to try something I haven't tried before. I am going to make a global object that I can call functions on from any page since I have a setup in which all pages use a specific layout file.
So I got this setup here:
<html>
<header>
<css and meta stuff>
</header>
<body>
<navbar....>
<sidebar...>
<div id="render-body">#RenderBody</div>
<layout-footer....>
<script inclusions>
</body>
</html>
When #RenderBody() is called, an HTML page is served as the actual page that the browser receives, in-between the two div tags.
What I'm trying to then do, is to make a function which can hide the sidebar because you might not always need it and as such it should be possible to simply hide it.
So I wrote the following piece of code:
var UniHub = {
ToggleContextSidebar: function () {
var $sidebarAndBody = $("#render-body", "#context-sidebar");
$sidebarAndBody.toggleClass("hide-context-sidebar");
}
};
Which in theory should work right? But it doesn't. The code is called just fine, but #render-body and #context-sidebar are not found. When I debug I find that the $sidebarAndBody element has a length of 0. So toggleClass() doesn't actually apply a class to any of the two divs.
They are present at the time I press my test button:
So why could this be?
You're closing #context-sidebar then opening #render-body, so #render-body is not in the context (inside) of #context-sidebar. Hence no matching element.
EDIT: if you want both elements you could do:
$sidebarAndBody = $("#render-body, #context-sidebar");
If you only want to target the sidebar just use $("#context-sidebar");
EDIT: showing jQuery context:
console.log("# of body elems inside html:", $("body", "html").length);
console.log("# of body elems inside head:", $("body", "head").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<p> Some html </p>
<script> some script </script>
</html>
How to identify the script tag and render them as content.
I have a div dedicated to display a html in my webpage, and if it has any script I want to render them as content, but while appending the html to the div, the script gets executed which I dont want to happen. How to keep the script from executing, are there any libraries to do that.
Note:
1. The Inline script should also be prevent from executed.
2. The Html Content getting appended is dynamic and got from email listener source
Thanks in Advance!
but while appending the html to the div, the script gets executed which I dont want to happen. How to keep the script from executing, are there any libraries to do that.
Since you say you already have the div content and as soon as you append it the script gets executed, This is a default behavior, What we can do is before appending the div content of yours we can modify the content string to replace <script> and </script> by <script> and </script>. So here is the demo of it.
var divContent = '<script>alert("I must not execute!!");<\/script>';
var res = divContent.replace(/<script/g,"<script>").replace(/<\/script/g,"</script>");
document.getElementById("output").innerHTML = res;
<div id="output">
</div>
Use the document.ready(); method. This will only run your JavaScript once all the HTML elements have rendered. Better yet, wrap your function within the jQuery shorthand:
$(function() {
alert( "DOM elements rendered!" );
});
You can try to use jQuery document.ready(); function to only allow the script to execute when the page has loaded.
I have a popup window working with the following code, but I need to amend it to apply a CSS class to either the HTML tag or the Body tag, so I can style the popup window differently than the normal site.
Here's the code I'm currently using:
<script language="javascript" type="text/javascript">
<!--
/****************************************************
Author: Eric King
Url: http://redrival.com/eak/index.shtml
This script is free to use as long as this info is left in
Featured on Dynamic Drive script library (http://www.dynamicdrive.com)
****************************************************/
var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);
}
// -->
</script>
I tried to add a line right after the win=window.open line that looked like this:
win.document.getElementById('body').className += " popup";
Unfortunately it didn't work. Any ideas on how I can make it so if a window is popped up using this javascript function it'll apply a CSS class to the window?
The HTML call to the function was with this code, if it matters.
<li>Play in pop up | </li>
Alternatively I've tried using this jquery version of a popup window (http://swip.codylindley.com/popupWindowDemo.html), but haven't figured out how to do it this way either. Thank you so much for your help, this has been killing me all day!
As you can see u are trying to reach object with id='body'.
However i think that your markup looks like
<body> ... </body>. If that's true then You can't use JS function getElementById because You have no ID on body element :)
The solution would be <body id='body'> ... </body>
Also You can use different JS function to select the body.
var body = document.getElementsByTagName( "body" );
win.document.getElementById('body')
will look for DOM element which matches the provided ID and in this case there is no element whose ID is body.
try to replace this with win.document.getElementsByTagName('body'). this should give you the body tag then you can apply the CSS class to it.
Since you will only have one body in your document you can directly assign the class to body tag in popup HTML itself.
I have a div on my page defined as follows:
<div id="scripts">
</div>
I want to dynamically change the contents of the div and load in some scripts using jQuery. I am doing it like this:
$('#scripts').html('<script language="JavaScript">pn = "landing page"; '+
'cms_1 = "content"; '+
'cms_2 = "promotional "; '+
'cms_3 = "campaign"; '+
'cms_s = "blk:us:dc"; '+
'cms_env = "dev"; '+
'cms_country = "USA"; '+
'<\/script>');
This is in the document.Ready function. However, when I view the source after the page is loaded, the div appears empty and I do not see the script tags. I thought that the script wasn't getting added but when I add alert("done"); to the script. I get the alert which tells me that the code is executed.
Why can't I see the changes made when I view the source? Is the Source html rendered before the document.ready function?
The html function from jquery internally uses the innerHTML property of the browser when available. In general, script blocks inserted via innerHTML don't get executed almost in any browser.
Try creating a script tag with the content and appending it to the document instead, e.g.
var script=document.createElement('script');
script.type='text/javascript';
script.html(...);
$("#scripts").append(script);
After seeing your motivation in the comment, I have to add : although you can later physically remove a script tag from the site, this won't have the effect of unloading its content (e.g. functions defined in the script). The only way to achieve that without refreshing the page is to encapsulate the objects defined in it and delete them manually. This is of course only possible if the content of the script was designed upfront in such a way.