I'm trying to run a script on images within specific blog posts. Each post div is given a unique ID by Blogger that I'm trying to get. Because I only want to run the script on posts containing the function call and not the entire page, I want the function to basically find the ID of the div that's calling it, store that ID as a variable, and then pass that variable in to my function.
<script>
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
</script>
This returns the correct element but the second I wrap it in a function(){} it doesn't work anymore. How can I assign these variables from within a function so I don'thave to clutter up every post's html with a bunch of variable declarations?
Secondly, once I have these variables assigned is there a way to use the value stored with the getElementByID method to actually select the element?
var parentDivID = parentTag.id;
var postID = document.getElementByID(parentDivID); //can't figure out how to select using this as the variable
For ease of use I'd like it if I could simply wrap the function call in script tags and stick it at the end of my post's html whenever I need to use it.
Details
The script I want to run finds images within divs with a specified class and resizes them to fit side-by-side so that the outer edges of the images completely fill the width of the div.
Here is the question covering that script:
Force dissimilar images to equal heights so combined widths fill fixed div
I would like to call this script at the end of any post body where I plan to use side-by-side formatting. The reason I want to call it at the end of a post instead of on the entire page is because the page uses "infinite scrolling" and I'm worried that as posts load after the fact the resizing script will have already been run and newly loaded posts will not be resized.
So I want the function to be able to find the unique ID of the div that contains the call, use that as a variable and ask the script to look inside that post for divs of a certain class, then look within those divs for image tags and resize those images. I hope that makes sense.
Here's an example of what I'd like the post's html to look like:
<div style="width:500px; margin:auto;">
<div class="widthVal x2">
<img class="caption" alt="Caption 01" src="sample01.jpg" />
<img class="caption" alt="Caption 02" src="sample02.jpg" />
<img class="caption"alt="Caption 03" src="sample03.jpg" />
</div>
<script> resizeMagic(); </script>
</div>
Thanks for any help!
Related
I would like to generate something to display that looks like the Facebook app previews using plain javascript. I already have the image url, title, and description data. However, I have no idea where to start with rendering exactly like the following:
google maps preview
Usually, how do you accomplish this in javascript? Do you have to manually specify the CSS? I'd really appreciate any advice and resource suggestions. I'm very new to javascript and UI.
So our goal is something like:
<div class="containerDiv">
<img src="blah blah">
<div>
<div class="urlDiv">my.url.com</div>
<div class="titleDiv">My title</div>
<div class="descriptionDiv">My description</div>
</div>
</div>
You will of course need to style a bit. Your page typically loads a lot of css style sheets. To one of them, you can add the css that will style your new "component". As an example:
<style>
.containerDiv {
display:flex;
align-items:center;
border:solid 1px gray;
/* etc... */
}
.containerDiv > img { /*...style for the image...*/ }
/*...more styles...*/
</style>
My answer will not include the correct css. Learning css in depth by is itself long proccess, so be patient. Follow a good CSS tutorial in case you need it.
Let's go on. The next step is to render the above markup with js.
To achieve this with plain js, use the native functions:
1) document.createElement to create a new element. This returns a js object containing the html element representation. This is not appended yet to the document. It is not visible, not yet a part of the page.
2) You can manipulate this object using: setAttribute(). Attribute is everything that follows your tag name. For example, to set the src of an image call:
const myImg = document.createElement("img");
myImg.setAttribute("src", "https://my.cool/image.png"); //the image is still not visible, because we did not yet append it into the DOM...
3) We use innerHTML property and/or append child to add elements within other elements (you typically start by creating the outer most element, create each child one by one and call appendChild of the parent to add each child).
4) Once you are ready creating your whole element, append it anywhere you like in the document, and it will become visible:
const myCoolElement = document.createElement("div");
//do stuff
document.body.appendChild(myCoolElement); //this will put it at the end of the page
//or, alternativelly
document.querySelector(".myElement > #thatWillHost .my .newComponent").appendChild(myCoolElement); //to append it somewhere else.
As a side note, querySelector and querySelectorAll will be also useful functions to you. Using querySelector, you can append your new element anywhere in the page that you like.
As a conclusion, you can react and manipulate the document through js by using tha mentioned (and many more) functions that are available out-of-the-box in every browser.
I have been trying to get the names of the visible div inputs there are two visible..!
but it's getting difficult for me..I got a way out with javascript but I really want to to do it in PHP..! as names of divs and inputs are changing on every visit and reloading the page..! so it's quite difficult to target by any permanent name or ID..!
Here is how I got it from a user in javascript :
var isCandidateRegion=function(node){
return (node.innerText.indexOf('Username')>-1 && node.innerText.indexOf('Hours')>-1);
};
//Find the last table in th document that contains 'Username' and 'Hours'
var candidateRegions=[].filter.call(document.querySelectorAll('table'),isCandidateRegion);
var targetRegion=candidateRegions[candidateRegions.length-1];
var isVisible=function(node){
return (node.offsetWidth && node.offSetWidth >0) || (node.offsetHeight && node.offsetHeight>0);
};
var inputs=[].filter.call(targetRegion.querySelectorAll('input'),isVisible);
var usernameInput=inputs[0].name;
var hoursInput=inputs[1].name;
console.log(usernameInput,hoursInput);
So what I want is to get the names in a php variable so that I can use it in php now..I can see the names of the inputs in console but I want it to store in a PHP variable..!
So if there is any way please or alternative of using jQuery or Javascript as PHP will be great..!
PHP is a server side language which for all intents and purposes relating to how I understand your question, is basically there only to serve and read HTML code. Unless you have something actually written on a DOM element, there is no way for PHP to know whether it is visible or not, as it can't automatically detect its styling like JavaScript can.
JavaScript on the other hand is designed for working with DOM page elements and detecting styles, or manipulating elements.
To make your PHP see what elements are visible, you need to explicitly tell PHP what is and isn't visible by putting it into HTML using JavaScript (or jQuery). This can be done by:
Adding a specific class onto your div that you want to make known to PHP e.g. <div class="visible"> ... </div> or <div class="hidden"> ... </div>.
Adding a data attribute to your element e.g. <div data-visibility="visible"> ... </div> or <div data-visibility="hidden"> ... </div>
In your PHP, on the method reading info from the page you can traverse the DOM and get all div's that have the appropriate class or attribute.
I have a div tag in in my JSP page. Its ID is autopopulated by other parameters that I don't have control over.
The div tag looks like this. I am skipping the contents in the div in this post.
<div class="parallax styleswitch" id="${nodeId}" style="${desktopstyle}" data-large="${desktopstyle}" data-medium="display:none;" data-small="display:none;" data-dtautoheight="true" data-tabautoheight="false" data-mobautoheight="false">
I want to calculate the height of this div. I was able make that work for div with static ID
$(".testt").height();
http://jsfiddle.net/m7cyw70y/
How can I use the nodeId variable value in the JS to get the div's height? My JS code is in in the JSP page wrapped around script tags.
In the JS code, use the auto-populated parameters to your benefit on server-side:
var nodeToGetHeight = "${nodeId}";
$("#" + nodeToGetHeight).height();
These auto-populated parameters could be used to populate an array that could then be looped through for multiple heights.
You can use another attribute instead of the id. An example using the class attribute:
$('div.parallax').height();
You can also use a custom attribute:
<div custom-attr="myCustomAttr"></div>
$("div[custom-attr='myCustomAttr']").height();
There are even more approaches.
On the JSTL page I have following divs
<div dojoType="dijit.layout.TabContainer" style="width: 100%; height: 100%;" doLayout="false" id="dojoTabbedPane" >
<c:forEach items="${summariesMap}" var="summaryEntry">
<div dojoType="dijit.layout.ContentPane" title="${summaryEntry.key}">
I try to find all divs under (including dojoTabbedPane) in order to recersively destroy all the contentPane under it. Then I can use jQuery.load() to reload contents and use
dojo.parser.parse(dijit.byId("dojoTabbedPane"));
to re-parse the component to make sure the tabbedPane can be rendered(otherwise it doesn't and cause memory leak or error)
Here the question is:
(1) Am I on the right track to re-parse the dojo TabbedContainer?
(2) Why each time the findWidgets function just return array with size 0?
Thanks in advance.
I'll answer 2 first: because dijit.findWidgets expects a DOM node, not a widget. If you need to find all widgets inside another widget, you can use getDescendants instead:
var descWidgets = dijit.byId("dojoTabbedPane").getDescendants();
Onto question 1: First off: if you want to destroy all the tabs in a TabContainer, you can use :
dijit.byId("dojoTabbedPane").destroyDescendants();
Now, if I understand you correctly, you subsequently grab a string of HTML from the server (using jQuery), and want to add it to the TabContainer. This new content contains several ContentPane divs, and you want these to become the new tabs in the TabContainer.
I may be wrong here, but I don't think that's doable without some gnarly hack. Once you've parsed/instantiated a TabContainer, you should add tabs using addChild, passing instantiated ContentPanes.
This means that if you get new HTML content like this from the server (via your jQuery load):
<div dojoType="dijit.layout.ContentPane" title="new tab1">foo</div>
<div dojoType="dijit.layout.ContentPane" title="new tab2">bar</div>
.. then your best bet is to remove the old TabContainer and make a new one, then parse the whole thing. If you're able to change the content you get from your server, perhaps you can simply wrap that in <div dojoType="dijit.layout.TabContainer....
I want to give a static javascript block of code to a html template designer, which can be:
either inline or external or both
used once or more in the html template
and each block can determine its position in the template relative to the other javascript code blocks.
An example could be image banners served using javascript. I give code to template designer who places it in two places, once for a horizontal banner in the header and once for a vertical banner. The same code runs in both blocks but knowing their positions can determine if to serve a horizontal or a vertical image banner.
Make sense?
Another example: Say you have the same 2 javascript tags in a web page calling an external script on a server. Can the server and/or scripts determine which javascript tag it belongs to?
NOTE: Can we say this is a challenge? I know that I can avoid this puzzle very easily but I come across this on a regular basis.
JavaScript code can locate all <script> elements on the page and it can probably examine the attributes and the content to check from which element it came from. But that's probably not what you want.
What you want is a piece of JavaScript which replaces tags on the page with ad banners. The usual solution is to add a special element, say a IMG, for this and give that IMG an id or a class or maybe even a custom attribute (like adtype="vertical") and then use JavaScript to locate these elements and replace the content by changing the src attribute.
For example, using jQuery, you can should your images like so:
<img src="empty.gif" width="..." height="..." class="ad" adtype="..." />
Then you can locate each image with
$('img.ad')
[EDIT] Well, the server obviously knows which script belongs into which script tag because it inserts the script. So this is a no-brainer.
If the script wants to find out where it is in the DOM, add something which it can use to identify itself, say:
<script>var id= '329573485745';
Then you can walk all script tags and check which one contains the value of the variable id.
If you call an external script, then you can do the same but you must add the ID to the script tag as you emit the HTML:
<script id="329573485745" src="..." />
Then the external script can examine the DOM and lookup the element with this id. You will want to use an UUID for this, btw.
This way, a piece of JS can locate the script tag which added itself to the page.
Best thing would probably be to make an insert once function, and then have him insert only the function call where needed.
Like this:
timescalled=0
function buildad(){
var toinsert="" //Code to generate the desired piece of HTML
document.write(toinsert)
timescalled+=1 //So you can tell how many times the function have been called
}
Now a script block calling the function can simply be inserted wherever a banner is needed
<script type="text/javascript">buildad()</script>
Thanks for the tips everyone but I'll be answering my own question.
I figured out several ways of accomplishing the task and I give you the one which works nicely and is easy to understand.
The following chunk of code relies on outputting dummy divs and jQuery.
<script>
// Unique identifier for all dummy divs
var rnd1="_0xDEFEC8ED_";
// Unique identifier for this dummy div
var rnd2=Math.floor(Math.random()*999999);
// The dummy div
var d="<div class='"+rnd1+" "+rnd2+"'></div>";
// Script which :
// Calculates index of THIS dummy div
// Total dummy divs
// Outputs to dummy div for debugging
var f1="<script>$(document).ready(function(){";
var f2="var i=$('."+rnd1+"').index($('."+rnd2+"'))+1;";
var f3="var t=$('."+rnd1+"').length;";
var f4="$('."+rnd2+"').html(i+' / '+t);";
var f5="});<\/script>";
document.write(d+f1+f2+f3+f4+f5);
</script>
Why not not just place the function call on the page instead of the entire code block? This way you can pass in a parameter to tell it what type of advertisement is needed?
BuildAd('Tower');
BuildAd('Banner');
Javascript itself has no clue of it's position in a page. You have to target a control on the page to get it's location.
I don't think it is possible for JavaScript code to know where it was loaded from. It certainly doesn't run at the point it is found, since execution isn't directly tied to the loading process (code usually runs after the whole DOM is loaded). In fact, in the case of externals, it doesn't even make sense, since only one copy of the code will be loaded no matter how many times it is encountered.
It shouldn't be the same code for each banner - there will be a parameter passed to whatever is serving the image banner which will specify the intended size.
Can you give a specific example of what you need this for?
To edit for your recent example: The simple answer is no. I could help you approach the problem from a different direction if you post details of your problem
The term "static block of code" leaves a lot of room for interpretation.
Inline scripts (e.g., ones that rely on document.write and so must be parsed and executed during the HTML parsing phase) cannot tell where they are in the DOM at runtime. You have to tell them (as in one of the first answers you got).
I think you'll probably find that you need to change your approach.
A common way to keep code and markup separate (which is useful when providing tools to HTML designers who aren't coders) is to have them use a script tag like so:
<script defer async type='text/javascript' src='pagestuff.js'></script>
...which then triggers itself when the page is loaded (using window.onload if necessary, but there are several techniques for being triggered earlier than that, which you want because window.onload doesn't trigger until the images have all loaded).
That script then looks for markers in the markup and manipulates the page accordingly. For instance (this example uses Prototype, but you can do the same with raw JavaScript, jQuery, Closure, etc.):
document.observe("dom:loaded", initPage);
function initPage() {
var verticals = $$('div.vertical');
/* ...do something with the array of "vertical" divs in `verticals`,
such as: */
var index;
for (index = 0; index < verticals.length; ++index) {
vertical.update("I'm vertical #" + index);
}
}
The designers can then have blocks on the page that are filled in by code which they flag up in a way that's normal for them (classes or attributes, etc.). The code figures out what it should do based on the classes/attributes of the blocks it finds when it runs.