Code not dynamically updating itself - javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">
$.getJSON('http://anyorigin.com/get?url=microsoftwebpro.com&callback=?',
function(data){
$('#output').html(data.contents);
$('a').each(function() {
$(this).attr('href', 'http://anyorigin.com/get?url='+$(this).attr('href')+'&callback=?');
});
});
$('a').click(function() {
$.getJSON($(this).attr('href'), function(data) {
$('#output').html(data.contents);
});
});
But I can't seem to figure out why it isn't loading in the right order.
So for example, I want it to load the contents from another domain, then add an add filter href to all the links in the "output" div and only that div(not working)
And then if I click a link it updates the "output" div instead of actually navigating to the link.

One solution is to bypass changing the <a> elements and just capture the clicks. Since you're dealing with dynamically created elements, it will probably be easier to use Event Delegation:
function AnyOriginURL(url) {
return 'http://anyorigin.com/get?url='+url+'&callback=?';
}
function Navigate(url) {
$.getJSON(AnyOriginURL(url), function(data){
$('#output').html(data.contents);
});
}
// When clicking any <a> inside the #output...
$("#output").on("click", "a", function(e) {
// Prevent click from triggering navigation
e.preventDefault();
// And Navigate there using our method
Navigate($(this).attr("href"));
});
// Onload, start at this base page
$(function() {
Navigate("microsoftwebpro.com");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Take heed: When using this example, the website is very slow to load

Related

Get Child Attribute using JQUERY

I am creating a link gallery.
HTML:
<div class="link">
<header>Test Header</header>
Click Here
</div>
I want to go to the A element's URL when clicking anywhere in the div.
Javascript with JQUERY 3.2.1:
$(function() {
$("div.link").click(function() {
$url = $this.children("a").attr("href");
alert($url);
});
});
It doesn't alert the URL
I have also tried:
$(function() {
$("div.link").click(function() {
$url = $this.find("a:first-child").attr("href");
alert($url);
});
});
It returns a collection instead of a single element so I tried the following:
$function() {
$("div.link").click(function() {
$url = $this.find("a");
alert($url[0].attr("href"));
});
});
Neither approach is working. I have confirmed the click selector is functioning by testing it with a simple alert("hello");
EDIT: I was using $this instead of $(this).
I want to goto the A element's URL when clicking anywhere in the div.
Based on the code you have shared, $this seems to be undefined
If you just want to fetch the href property of the child anchor tag, then simply
$("div.link").click(function() {
var href = $(this).find("a").attr( "href" ); //attr will fetch the attribute of first element in the result of find
});
If you want to click on the child anchor tag, then try using one of the following ways
$("div.link").click(function() {
$(this).find("a").first().click();
});
or
$("div.link").click(function() {
$(this).find("a").click();
});
or
$("div.link").click(function() {
$(this).find("a").trigger( "click" );
});
or if you just want to go the URL
$("div.link").click(function() {
window.location.href = $(this).find("a").attr( "href" );
});
If you want to get the href attribute when clicking on the div element, you can consider using the selector $(".nameOfDivClass"). On the element selected you will bind a function that will get your href.
$(".link").on("click", function(){
console.log($(this).children("a").attr("href"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
<header>Test Header</header>
Click Here
</div>
If you check your browser's console, you'll have an error saying $this is not defined. It should be $(this), in order to turn this (the raw HTML element clicked on) into a jQuery object on which you can the run jQuery methods such as .find() and .attr().
Additionally, this version will actually cause the navigation action rather than just alerting the URL:
$("div.link").click(function() {
$(this).find("a").click();
});

Click anywhere in the page to close div

I have an overlay div that fades in when I click on a DOM element. I would like to be able to close it when I click anywhere on the page ( except the div itself) but it does not work..
Here is my code:
//Script for showing the DIV called overlay.
<script>
$(function() {
$('#loginfooter').click(function(){
$('#overlay').fadeIn(200,function(){
$('#box').animate({'top':'20px'},'slow');
});
return false;
});
$('#boxclose').click(function(){
$('#box').animate({'top':'-800px'},500,function(){
$('#overlay').fadeOut('fast');
});
});
});
</script>
//Script for hiding the div after clicking anywhere..
<script>
$(document).ready(function(){
$('#overlay').on('click',function(ev){
var myID = ev.target.id;
if(myID!=='overlay'){
$('#box').animate({'top':'-800px'},500,function(){
$('#overlay').fadeOut('fast');
});
}
});
});
</script>
Just replace this:
$('#overlay').on('click', function (ev) {
with this
$(document).on('click', function (ev) {
and try again....
Actually, when you are clicking on the overlay element, the myID variable value is always == 'overlay'. Hence, it never goes inside the if statement.
DEMO 1
$(document).on('click',function(e){
if(!$(e.target).closest('#overlay').length)
$('#overlay').hide();
});
Other possibility without using any delegate event:
DEMO 2
$('#overlay').on('blur', function (e) {
$(this).hide();
});
Even you'll see most people using the first method, using the second one will avoid to have to use any delegate event which is better IMO. You just have to set focus on overlay when open it or when added to DOM, depending your specific case.
Would this work for you: jsfiddle?
I changed this:
if(myID!=='overlay'){
to this
if(myID=='overlay'){
so that you target the overlay instead of the box.

Image not clickable after loaded via AJAX

I have a set of images that are loaded via jQuery AJAX. For some reason, my click handler won't trigger when it is clicked.
JavaScript:
$(document).ready(function()
{
$('img.delete_related_sub').click(function()
{
alert('testing');
});
//I added this part to test, because the above wasn't working...
$(document).click(function(event)
{
alert(event.target.tagName+' '+event.target.className);
});
});
HTML:
<img data-rsid="2" class="delete_related_sub" src="image.png" />
So my 2nd click handler alerts me with "IMG delete_related_sub". But the first one isn't triggered. The is actually in a table that is actually in a pane run by bootstrap tabs, not sure if that'd actually help though.
Try it like this
$(document).on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Just replace document with a static parent of your image.
Use this:
$("body").on('click', 'img.delete_related_sub', function() {
alert('testing');
});
Or, in the success: give this:
$('img.delete_related_sub').click(function() {
alert('testing');
});
Because the line to bind the event runs before the element is added, try using
$(parent).on('click', 'img.delete_related_sub', function() {});
where the parent is a static element that will be there for sure. This works because the event is bound to an element that actually exists, then checks to match your selector. See .on() for more details.
Something like
$(document).on('click', 'img.delete_related_sub', function() {});
would work fine.
$('.delete_related_sub').live("click", function()
{
alert('testing');
});
Use live event to listen clicks

Using jQuery replaceWith to replace content of DIV only working first time

I'm using the following jQuery to pull new data and replace the contents of the DIV listdata
$(function(){
$('.refresh').click(function(event) {
event.preventDefault();
$.ajax({
url: "_js/data.php",
success: function(results){
$('#listdata').replaceWith(results);
}
});
});
});
The script is triggered by numerous links on the page, such as:
Update 1
Update 2
For some reason the script only works on the first click of a link. Subsequent clicks do not refresh the data.
I've seen various fixes but nothing that I can get working. Any suggestions?
It looks to me like your problem is with using replaceWith.
You're removing the element which matches $('#listdata') on the first call of replaceWith, so subsequent refreshes can't find where the data is supposed to be placed in the document.
You could try something like
$('#listdata').empty();
$('#listdata').append(results);
or chained like this
$('#listdata').empty().append(results);
If you're using replaceWith(), you're replacing #listdata with a brand new element altogether.
If data isn't something like <div id="listdata"></div> then #listdata is disappearing after the replaceWith(). I'm thinking you should probably use html() instead.
You'll need to change the href's on your links to .... This prevents the browser from refreshing when you click the link.
If you're doing things this way, you'll also want to stick a "return false" at the end of the click handler to prevent bubbling.
Try:
$('a.refresh').live('click', function(e) {
e.preventDefault();
$.ajax({
url: '_js/data.php',
success: function(data) {
$('#listdata').empty().html(data);
}
});
});
If the .refresh anchors are inside the #listdata element, then delegation is a more optimized solution:
var list = $('#listdata');
list.delegate('a.refresh', 'click', function(e) {
e.preventDefault();
$.ajax({
url: '_js/data.php',
success: function(data) {
list.empty().html(data);
}
});
});

How to set an onClick attribute that would load dynamic content?

This code is suppose to add an onClick event to each of the a elements, so that clicking on the element would load the content of the page dynamically into a DIV.
Now, I got this far - It will add the onClick event, but how can I load the dynamic content?
$(document.body).ready(function () {
$("li.cat-item a").each(function (i) {
this.setAttribute('onclick','alert("[load content dynamically into #preview]")');
});
});
Thank you.
$(document.body).ready(function () {
$("li.cat-item a").click(function (e) {
$('#this-is-your-target-div').load(this.href);
e.preventDefault();
});
});
See the documentation for jQuery ajax functions here: http://api.jquery.com/category/ajax/.
$(document).ready(function () {
$('li.cat-item a').bind('click', function (e) {
$('#preview').load($(this).attr('href'));
e.preventDefault();
});
});
There is an extensive amount of AJAX functions in jQuery: http://api.jquery.com/category/ajax
$("li.cat-item a").click(function() {
$.get($(this).attr('href'), function(data) {
$("#preview").html(data);
});
});
Does an AJAX request using $.get which is more easier to read imho to the href attribute of the clicked element, and puts the retrieved data into the div preview.
Use $('div.container').html(htmlString);
where htmlString is the html code of the content you want to place inside the div with class container

Categories

Resources