Can't access elements loaded via ajax using jQuery - javascript

I need to modify content loaded via ajax, but can't seem to access it. I don't have access to the js file that is doing the initial load so I need to write a separate function to change the content.
The content needs to be modified automatically WITHOUT the user clicking or interacting with anything on the page.
In the example below the 'news' div is hard coded and the 'article' divs are loaded via ajax.
HTML
<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>
jQuery
$(document).ready(function() {
console.log( $("#news").html() );
});
Console
<div id="news">
</div>
How can I access the articles? I want to remove '_small' from the img src.
Thanks!

This should work:
$(document).ajaxStop(function() {
$("#news").find('img').attr("src", function(_, src){
return src.replace('_small', '');
});
});

How can I access the articles? I want to remove '_small' from the img src.
For example like this:
$('#news .article img').attr('src', function() {
return this.src.replace('_small', '');
});
You can execute this code on AJAX successful completion
$(document).ajaxSuccess(function() {
// above code
});

You said the article divs are loaded through AJAX, seems that this script is running before they are loaded. Try putting this script after #news so all the content is already loaded when it is executed.
<div id="news">
<div class="article"><img src="headline1_small.jpg">
<div class="article"><img src="headline2_small.jpg">
<div class="article"><img src="headline3_small.jpg">
</div>
<script>
$(document).ready(function() {
console.log( $("#news").html() );
});
</script>

To remove "_small" from src of the img tag, there is another way for that. you dont need to get access to the html() -> innerHTML of the #news div.
all you could do is get hold of the all the ".article" div's and then alter the img tag.
$(".article img").each(function() {
$(this).attr('src', $(this).attr('src').replace("_small", ""));
});
Thanks

Related

How do I change placeholder content in javascript per page

How do I update content loaded with Jquery .load() with javascript?
I'm using two placeholders on every page: one with the navigation bar, and one with the main skeleton of the content, like this:
<body>
<div id="nav-placeholder">
</div>
<div id="content-placeholder">
</div>
</body>
The nav bar and content are both in seperate files and are loaded into the pages with an external javascript file like this:
$(function(){
$("#nav-placeholder").load("nav.html");
});
$(function(){
$("#content-placeholder").load("content.html");
});
So far, it all works nicely. Now, I'm trying to alter the content separately for each page (with JS)
Part of content.html is for example
<h2 id="subheader1">Title</h2>
I'm trying to change the #subheader1 content in the javascript file like so:
$(function(){
$("#nav-placeholder").load("nav.html");
});
$(function(){
$("#content-placeholder").load("content.html");
});
$(document).ready(function() {
document.getElementById("subheader1").outerHTML = "test" ;
});
but that doesn't work (this is aimed at all pages, but it still doesn't work). Probably because it's only seeing the placeholder DIV in index.html and not it's content?
I tried placing the subheader1 div in the index.html to test, and then it did work, but that would take away the efficiency of the placeholder.
Is there any way to do this (or another way to be more efficient with pages with the same (DIV) layout but different text?)
Thanks!
The load method is not synchronous, so
$(document).ready(function() {
document.getElementById("subheader1").outerHTML = "test" ;
});
is executed before the html is loaded in the page.
The doc suggest using a callback function.
it is executed after post-processing and HTML insertion has been performed
I had success using this in my js file:
$(document).ready(function() {
$(function(){
$("#nav-placeholder").load("./nav.html", function() {
document.getElementById("insideNav").outerHTML = "It works !" ;
});
});
});
with <h2 id="insideNav">Original Nav Bar</h2> in my nav.html.

Using .load in JavaScript

I am using .load() function in JavaScript and I'm working with JSP java files. I am loading a page like this in JavaScript
$("#body").load("livestatus #status")
The problem is the div I'm trying to load doesn't load immediately on page load because it contains some data from APIs, so there's a one second delay but my code doesn't accommodate that delay.
Try to put your code in document.ready block or if you are making an ajax request then put your code in Ajax success function
If you use jQuery and it just not initialized for some element, you can use
$(function() {
$("#body"). // ... your code
});
If it calls through some time and you can't track when exactly, you can use live listeners on some event. Like, click on this element.
$("body").on("click", "#body", function() {
// your code
});
$("body") can contain any parent element which had loaded before jQuery.
Or you can load 1px image with you code which loads after main code and track when it will load.
<div id="body">
<!-- your markup -->
<img class="loading-status-img" src="../path_to_1px_small_image.png" style="display:none">
<img class="loading-status-img-2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=" style="display:none">
<!-- your markup -->
</div>
<script>
$("body").on("load", ".loading-status-img", function() {
// execute you code here after #body will load
});
</script>
The second image is encoded with base64.
[UPD] old version of jQuery have another syntax. More: http://api.jquery.com/live/

Show hidden HTML elements with javascript

I have the following in the <body> of my HTML
<div class="exact">
<div> <a id ="button_some_id" href="#"> Toggle Hidden </a></div>
<div id="item_some_id" hidden>This is hided</div>
<script type='text/javascript'>
$("#button_some_id").click(function() {$("#item_some_id").toggle();});
</script>
</div>
Link to jfiddle
The idea here is I want someone to be able to click on the Toggle Hidden link and it will show some hidden content (and when it is clicked again, hide it). However the javascript is not being triggered. Any help is greatly appreciated
You haven't inputted JQuery or JQuery UI into your JSFiddle's resources. Once putting them in, it works:
https://jsfiddle.net/tj8o8gwf/2/
$("#button_some_id").click(function() {$("#item_some_id").toggle();}); //works fine
Look at the External Resources section on the left hand side of the fiddle.
You also need to make sure the DOM is loaded.
$( document ).ready(function() {
$("#button_some_id").click(function() {$("#item_some_id").toggle();});
});
You need to make sure that jQuery is inputted
$(document).ready(function () {
$("body").on("click", "#button_some_id", function () {
$("#item_some_id").toggle();
});
});
Try this
//HTML
<div class="toBeHidden" hidden>This is hided</div>
//JS inside your click
if ($(".toBeHidden").is(":visible"))
{
$(".toBeHidden").hide('slow');
}
else
{
$(".toBeHidden").show('slow');
}

Remove HTML Elements from JQuery AJAX load() Response

Is there a possibility to remove specific HTML Elements from a AJAX (load) Response before placing in to the container? In this case I want to remove the "#containerTop", including content, from the response.
Response (HTML):
<html>
<head></head>
<body>
<div id="containerMain">
<div>...</div>
<div id="containerTop">Content-to-remove-including-container-div...</div>
</div>
</body>
</html>
I've tried this, without success.
<div id="middle"></div>
<script>
$( "#middle" ).load( "http://<URL>",
function(response, status, xhr){
$response.remove('#containerTop');
});
</script>
Any ideas?
.load() inserts the content directly for you. It does not give you an opportunity to modify it before it is inserted. As such you have two options:
You can modify the content after it is inserted, but before it is painted in the .load() completion handler.
You can switch to .get() to get the content as data, then put it into a jQuery object, then modify it using jQuery methods, then insert the modified content into your page yourself.
Here's an example of the second option:
$.get("http://<URL>", function(data) {
var temp = $(data);
temp.find('#containerTop').remove();
$('#middle').empty().append(temp);
});
response.find(element).remove()
This works with me

Javascript Ajax JQuery

Here's my issue.
I have a javascript function that update a div when i click the proper link. And it is working.
Since i have cliked the link my div content is updated with another Javascript. This time to close it.
Its fairly simple but i cant get it to work and i dont know why!
Here is the code that is in the page when it load for the first time
The div id config_window
<div id="config_window" class="config_window">
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn"class="admin_btn">administration.</div>
<div id="test">test</div>
</div>
Now the Javascript that call for the update inside that div
<script language="javascript" type="text/javascript">
$("#admin_btn").click(
function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
}
);
</script>
So far it's working my div is getting updated and i see the new content. The new content is
<div id="conception" class="conception">Conception et design graphique Zéro Gravité.
</div>
<div id="admin_btn_x" class="admin_btn">Terminer.</div>
<script language="javascript" type="text/javascript">
$("#admin_btn_x").click(
function(){
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
}
);
</script>
i was expecting that same function to work but its not!! and i dont get why since the first one is.
Could it be becuse my second script is in the div that get updated??
Thanks!
I suspect it's because the element that the second handler is supposed to apply to doesn't exist until after the DIV is updated and the function applying the handler is executed before the DIV is updated -- therefore the handler is not applied. You might want to try using the live handlers for the click event so that it will apply to all elements matching the selector no matter when the element is added. You can add both handlers on page load and they will apply to the elements with those ids whether they are added dynamically or not.
<script type="text/javascript">
$("#admin_btn").live('click', function(){
$('#config_window').addClass('config_open');
config_set('config_window','open','var')
});
);
$('#admin_btn_x').live('click', function() {
$('#config_window').removeClass('config_open');
config_set('config_window','close','var')
});
</script>
Is there a reason you add divide the function into two scripts? I would change your script to something like this:
<script type="text/javascript">
$(document).ready(function() {
$('#config_window').hide(); // just in case
$('#admin_btn').bind("click", function() {
if($('#config_window').is(':hidden')){
$('#config_window').show();
config_set('config_window','open','var')
} else {
$('#config_window').hide();
config_set('config_window','close','var')
}
});
});
</script>

Categories