Applying javascript to a dynamically added element - javascript

I've searched other articles and jQuery documentation, but have not quite found (or understood) the solution I need.
I'm including Sharing buttons on our site using another online service. The procedure is to add a snippet of HTML (a closed with a specific class name) and include a call to their Javascript file.
<div class="specific_class_name"></div>
<script type="text/javascript" src="path to script.js#pubid=my-account-id" async="async"></script>
This works well on pages for which I have access to edit HTML and include scripts.
My challenge is how to include the Share buttons on pages for which I only have access to run Javascript and not to include specific HTML. I can add the closed element using jQuery .append and include the Javascript call, but this does not work as needed. If I inspect the page after it is fully loaded, I see that the dynamic element has been added correctly and the script has been called. Viewing the Page Source, the is not present.
Of course, I have no means of editing this service's script. I need the called script to find the dynamic element either during or following page load, not following any user / mouse action.
Thanks for any feedback.

Create the div and then use the getScript command to include it like:
$(window).on('load', function(){
$('<div class="class_name"></div>').appendTo("someIDyouhave");
$.getScript('path to script.js#pubid=my-account-id');
});
http://api.jquery.com/jquery.getscript/

Have you tried something like this? Append the element and then add a click event?
$(function() {
var appendedElement = $('<div id="myID"></div>')
$('.specific_class_name').append(appendedElement).on('click', '#myID', function(){
whatever();
});
});
This should work.

Related

Loading mulitple LinkedIn share buttons dynamically and asynchronously

I have a page showing thumbnails of posts. The posts are fetched via AJAX and a filter allows for different posts to be fetched. When a thumbnail is clicked, a carousel opens centered on the clicked post. Each post in the carousel has a LinkedIn share button.
Linked share buttons don't work properly if loaded into an invisible element and then loaded later. So we must load them at the time of opening the carousel. I do this using the following code:
$.getScript('http://platform.linkedin.com/in.js', function() {
$('.li-box-1').append('<script type="IN/Share" data-counter="right"></script>');
});
Now, if I close the carousel and select a filter, thereby fetching a different set of posts, and then click on one of them, the carousel displays without the LinkedIn share button, and we get this warning in the console:
duplicate in.js loaded, any parameters will be ignored
This is because we've already loaded LinkedIn's in.js. Does anyone know how to get around this?
This is the code that calls in the required linked in .js library.
We check to see if the library has been loaded previously by checking if the variable IN is undefined. And based on that we load the library for the first time, or ignore it.
This code you will put somewhere in your <header> tag, after the <body> tag, or right before the </body>, dont know your situation.
<script>
if (typeof (IN) !== 'undefined') {
// IN.parse(); // old but still supports
IN.init(); // reinitiating linkedin button
} else {
$.getScript("http://platform.linkedin.com/in.js");
}
</script>
or alternatively you could do this:
<script>
delete IN;
$.getScript("http://platform.linkedin.com/in.js")
</script>
And now this code you will place with your specific carousel, or carousel items.
<script type="IN/Share"
data-url=" **code to generate your url** "
data-counter="right">
</script>
If you look at the script you're running, you'll see that the results of the .getScript isn't being loaded into the script tag or anything like that, but rather you're essentially performing two seperate actions: loading the script and then creating the tag with type="IN/Share". The initial action, loading the script, only needs to be run once, as you've discovered, so you just need to run that .append line to create whatever dynamic buttons you want and then call IN.parse() to link the script to the newly created elements.
Seems like you're doing some really amazing coding gymnastics just to be able to share a link on LinkedIn. Why not try something simpler?
https://www.linkedin.com/sharing/share-offsite/?url={url}
Then you can hyperlink anything you want, control it with whatever CSS and JS you want, etc..
Source: Microsoft LinkedIn Share URL Documentation.
For example, this works for me:
https://www.linkedin.com/sharing/share-offsite/?url=http://www.wikipedia.org/
Works fine:

Adding CSS Class Based on URL with Javascript or Jquery within Wordpress Template

I am attempting to write a small script which will look at page URL and, based on what URL it sees, add a new class to an HTML element. More specifically, on this page:
http://pamaphilly.wpengine.com/volunteer/
I'm going to add a class for the active URL which will add an arrow marker to the appropriate left hand nav marker. I have tried this strategy: jQuery add class based on page URL and, when I used the script on a dummy page, it works fine. But when I try adding it to the Wordpress Template, nothing happens. I've tried adding the script at the bottom of the template file and just (as a test) embedding it in the php template. I'm guessing my failure relates to a Wordpress issues (probably a failure of knowledge on how to do this) but I would appreciate any guidance.
Thanks.
You need to include .slick before you can use it. (before script.js + in the same way you include your script.js file)
Why not do this with CSS and WordPress directly, and skip JavaScript?
You can use WordPress's body_class() function to dynamically add a class to the <body> of your page. Using CSS, you can then target your appropriate .volunteer .sidebar-member li via CSS.

Load a html page in a div by clicking an image

I have an image and i want, once i click it, that a particular html page is displayed into a specific div. I found several answer yet, but none of them seems to work.
I'm thinking something simple with jquery, like the answer given here: display html file in a div
What's your solution ?
Thanks in advance.
EDIT1
I want to load an internal html page ( not an external page from another webiste ) by clicking an image.
This is the code i used taking example from the answer on the link above.
<script type="text/javascript">$(document).ready(function(){$("mainscreen").load("/home/dontrythisathome/Programmazione/HTML/Progetto-Corso-Inglese/Misc/FILE/HTML/ChiSiamo.html");}</script>
"mainscreen" is the final div when i want to display the html page.
Inside the function .load() there is the path of the html page.
But no html page is displayed into the div.
EDIT2: I found the silly mistake. I use this structure: when the correct position of the elements is . I could remove also the element but i'm using CSS and i'm more comfortable to place elements than using tag options instead. Thanks for all your replies. Tomorrow i'll see if the code with jquery works.
I think your Problem is, that when you load another website using .load().
All the other websites CSS/JavaScript gets loaded and yours gets overwritten.
Could you tell us, what you are trying to accomplish?
Are you loading a html-page from your own website or an external url?
If you dont care for the styles that other website uses, you could do something like this:
.load("example.com/some.html #content");
This loads the url you specifies and just copys the content of the HTML-Element that corresponds to this selector into your target element. (ONLY INLINE-CSS will be applyed that way, you would need to do that styling manually)
EDIT: Thank you for updateing your question.
You are trying to load a file from your filesystem.
Add file:// in front of the path to your .html file.
NOTE: Especially when you are trying to use AJAX you should use a local website and work with relative paths! This makes it much easier to deploy the website afterwards as you do not have to rewrite all your URLs.
Here is jsFiddle
Your html code
<img class="img" src="http://www.lessons4living.com/images/penclchk.gif" width=100 height=100>
<div class="targetDiv"></div>
Your javascript
$(document).ready(function(){
$(".img").click(function(){ //capture the event and ignite your work
loadPage("http://fiddle.jshell.net/"); //call our function
});
});
function loadPage(link){
$.get(link,function(data){ //dont forget cross-browser rules.
$(".targetDiv").append(data) //appended in to your div
})
};
Or you can use .load function with link parametre.
Lets say you have the following HTML code.
<div id="mainscreen">click on the image to load html …</div>
<img id="js-image" src="http://cl.ly/image/0A1P1s3r2M0u/Bildschirmfoto%202014-05-24%20um%2021.59.23.png" />
And some JavaScript code (with jQuery).
var image = document.getElementById('js-image'),
mainscreen = document.getElementById('mainscreen');
$(image).on('click', function() {
$(mainscreen).load("http://fiddle.jshell.net/florianpircher/tmRy9/show/");
});
Demo: http://jsfiddle.net/florianpircher/6wXBu/1/
You can not use $("mainscreen") because that would select <mainscreen> and not #mainscreen. In jQuery, you need a CSS-selector (like $("#mainscreen")).

How to run scripts loaded dynamically with javascript

I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.

jQuery: dynamicly generate iframe and run $.ajax(..) in it

I'm trying to run an $.ajax()-call inside of an dynamicly with jQuery generated iframe.
So somehow the jQuery instance needs to get passed into the iframe after it was generated and then then "$.ajax()" must get called... maybe with eval?
So to be clear, not only the iframe should get generated dynamicly, also the content inside the iframe (the JavaScript) should get generated and executed on the fly. And the dynamicly generated JavaScript inside the iframe should be able to use the jQuery instance of the script it was generated by to make use of $.ajax().
Hopefully it's somehow clear what I mean :-)
I'm happy about any suggestions.
I would suggest creating an iframe dynamically and appending using jQuery. Afer that set src to a basic page you have already created that contains:
<script type="text/javascript">
$(document).ready(function() {
$.ajax(...)
});
</script>
That should ensure that the page fires off your ajax request once it's loaded in the iframe.

Categories