How to select new loaded elements in jQuery without any event - javascript

I am working on a jQuery project which a part of page is loaded by choosing different options usign load() method.
I have this line in my application:
$('.pe').myFunction();
This code must be executed without any event. So I can not use any code like this:
$(document).on('click','.pe',function(){...});
It works well on all preloaded elements with pe class.But it does not work on new loaded contents which have same class.
Can you help me please?

The arguably correct way of doing it is using $(document).on('.pe','click',function(){...});; however, I did program a fair amount before I discovered that. So, I know there are a couple of work around. I'd use a class to mark an item as 'completed' after adding a click event.
If you have any 'hook' to know when the new html is added you can simply call a function that instead of using an interval.
Note regarding the question: you did say no events and this uses no events.
//Simulating ajax loading
setInterval(function () {
$(document.body).append('<button class="clickable">So clickable!</button><br />');
},1000);
//Your code
setInterval(function () {
$(".clickable:not(.completed)").click(function () {
console.log('works!');
}).addClass("completed");
},10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button class="clickable">So clickable!</button>
</div>

Finally I found the answer. I just put the same code inside the loaded page.
// New page which will be loaded with its all contents ...
<script>$('.pe').myFunction();</script>

Related

Rerun Jquery function onclick

I have a simple jquery script that changes the url path of the images. The only problem is the doesn't apply after I click the load more button. So I'm trying to do a workaround where it calls the script again after clicking the button.
<script type='text/javascript'>
$(document).ready(function ReplaceImage() {
$(".galleryItem img").each(function() {
$(this).attr("src", function(a, b) {
return b.replace("s72-c", "s300")
})
})
});
</script>
HTML
Load More
While Keith's answer will get you what you are looking for, I really can't recommend that approach. You are much better off with something like this.
<script type="text/javascript">
$(function() {
var replaceImage = function() {
$('.galleryItem img').each(function() {
$(this).attr('src', function(index, value) {
return value.replace('s72-c', 's300');
});
});
};
replaceImage();
$('.js-replace-image').on('click', replaceImage);
});
</script>
Using this html
<button class="js-replace-image">Load More</button>
By taking this approach, you do not expose any global variables onto the window object, which can be a point of issue if you work with other libraries (or developers) that don't manage their globals well.
Also, by moving to a class name and binding an event handler to the DOM node via JavaScript, you future proof yourself much more. Also allows yourself to easily add this functionality to more buttons very easily but just adding a class to it.
I updated the anchor tag to a button because of the semantics of what you need to do - it doesn't link out anywhere, it's just dynamic functionality on the page. This is what buttons are best served for.
I'd also recommend putting this in the footer of your site, because then, depending on your situation, you will already have the images updated properly without having to click the button. The only need for the button would be if you are dynamically inserting more images on the page after load, or if this script was in the head of your document (meaning jQuery couldn't know about the images yet).
I hope this helps, reach out if you have questions.

Re-serving a sites javascript dynamically

I would like to dynamically load a javascript file and undo what was done with the static javascript i have on my site. the static javascript i want to edit is
document.getElementsByTagName('script')[3]this is what im trying to do:
document.getElementsByTagName('script')[3].attributes[2].value = "http://differentlocation.com/jsfile.js"
The thing is when the source is altered I want all the other functions i had statically cached to go away. how is this possible?
*reworded. The sites current javascript attaches event handlers and does all kinds of functions, i would like to make all of these go away. Basically I am reloading a Almost exact copy of the javascript and dont want certain handlers active. etc
Or is there a way to blank out all of the pages current javascript, Just make it all useless, and then Load my new javascript
It looks like you're not using jQuery. If you were, this simple line of code should remove all event handlers from every element in your document:
$("*").off();
It might be worth exploring.
I'm unable to get the JavaScript to run again, most likely: it needs to be linked (which jsFiddle doesn't allow). Here's a demo.
In this example, we have three buttons.
<button id="myButton">Add an event listener for the bellow</button>
<button id="listener">Do something</button>
<button id="reset">reset</button>
We can then add event listeners,
// Do some stuff
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("listener").addEventListener("click", function () {
alert("I do something!");
});
});
... and at some point, reset the page. This works by taking the current HTML content out of the page, and having it stored in a variable. We then put it back in, causing all bindings to elements to be removed. It also has the harmful side effect of not running inline scripts.
// Soft reload of the page
document.getElementById("reset").addEventListener("click", function () {
var html = document.documentElement.innerHTML;
document.documentElement.innerHTML = "";
document.documentElement.innerHTML = html;
});

Scripts not running when using get function in jquery

I'm using the $.get() function to extract some data from my site. Everything works great however on one of the pages the information I need to extract is dynamically created and then inserted into a <div> tag.
So in the <script> tag, a function is run and then the data is inserted into <div id="infoContainer"></div>. I need to get the information from #infoContainer, however when I try to do so in the $.get() function, it just says it's empty. I have figured out that it is because the <script> tag is not being run. Is there another way to do this?
Edit:I am making a PhoneGap application for my site using jQuery to move content around so it's more streamlined for mobiles.
This is the code on my page:
$(document).ready(function () {
var embedTag = document.createElement("embed");
var infoContainer = document.getElementById("infoContainer");
if (infoContainer != null) {
embedTag.setAttribute("height", "139");
embedTag.setAttribute("width", "356");...other attributes
infoContainer.appendChild(embedTag);
});
});
As you can see, it puts content into the #infoContainer tag. However, when I try to extract info from that tag through the get function it shows it as empty.I have done the same to extract headings and it works great. All I can gather is the script tag is not firing.
This should provide you the contents of the element:
$('#infoContainer').html();
Maybe your script is executing before the DOM is loaded.
So if you are manipulating DOM elements you should wait till DOM is loaded to manipulate it. Alternately you can place your script tag at the end of your HTML document.
// These three are equivalent, choose one:
document.addEventListener('DOMContentLoaded', initializeOrWhatever);
$( initializeOrWhatever );
$.ready( initializeOrWhatever );
function initializeOrWhatever(){
// By the time this is called, the DOM is loaded and you can read/write to it
$.getJSON('/foo/', { myData: $('#myInput').val() }, onResponse);
function onResponse(res){
$(document).html('<h1>Hello '+res+'</h1>');
};
};
Otherwise... post more specifics and code
You have no ID to reference. Try setting one before you append
embedTag.setAttribute("id", "uniqueID");
It looks like you are wanting to use jQuery, but your example code has vanilla JavaScript. Your entire function can be simplified using the following jQuery (jsFiddle):
(function () {
var embedTag = $(document.createElement("embed"));
var infoContainer = $("#infoContainer");
if (infoContainer.length) {
embedTag.attr({"height": 139, "width": 356});
infoContainer.append(embedTag);
}
console.log(infoContainer.html()); // This gets you the contents of #infoContainer
})();
jQuery's .get() method is for sending GET requests to a server-side script. I don't think it does what you are wanting to do.

time javascript

I have the following problem: on a customer's homepage the navibar is loaded by javascript, but I need to change some URL's on it. If I just start my script on $(document).ready() it runs before the customers script and has no effect. I only can use setTimeout for my function to wait until the other script is ready, but it's not good or safe at all. I can't change anything on the website, only add a javascript - is there a way to time it after the other one?
You can use repeated setTimeout, in order to check if menu is accessible.
function check_menu(){
if(document.getElementById('my_menu')==null){
setTimeout('check_menu()',500);
} else {
//do some stuff
}
}
If you have information about the menu like the id or class, use the onLoad() jQuery method on the element. For example if the code is loading asynchronously, and you add the onload to one of the last elements it should fire after the content has finished.
$.post('AsyncCodeLoad.php', function(data) {
$('#lastElementToLoad').onLoad(RunMyFunction);
});
Or if you have no chance to insert your code into the async loading just add to the bottom of the </body>:
$('#lastElementToLoad').onLoad(RunMyFunction);
Just a thought.
Yes, add your script at the bottom of the <body /> tag to ensure it does not run until all other scripts have run. This will only work however if your customer is loading the nav links synchronously.
If the nav is being loaded asynchronously, use JS's setInterval to repeatedly check the contents of the nav for links. When you determine the links have been added, cancel your interval check and call your script's logic entry point.
Cheers
Fiddle: http://jsfiddle.net/iambriansreed/xSzjA/
JavaScript
var
menu_fix = function(){
var menu = $('#menu');
if(menu.length == 0) return;
clearInterval(menu_fix_int);
$('a', menu).text('Google Search').attr('href','http://google.com');
},
menu_fix_int = setInterval(menu_fix, 100);
HTML
<div id="menu">Bing Search</div>​

How can I tell when all images on a page are loaded using jQuery?

I’m using jQuery for my project. $(function(){...}) fires the function “when the DOM is ready” — this doesn’t say that all images are loaded, right?
Is there an event that gets fired when every image is loaded too?
I guess you mean
http://api.jquery.com/ready/
versus
http://api.jquery.com/load-event/
Example: Run a function when the page is fully loaded including graphics.
$(window).load(function () {
// run code
});
without jQuery:
window.onload=function() {
alert(document.images.length);
}
You can check on load event of image tag. This will get fired when image loading completes.
$("img").load(function(){
// your code
});
window.onload will solve this, I wrote about this there: http://amrelgarhy.com/blog/how-to-tell-when-images-have-loaded/

Categories