I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">
onclick of each i use next function:
function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();
var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
isParentools = 1;
var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;
$("#ratingModal").on("show.bs.modal", function (e) {
$.ajax({
url: url,
cache: false,
dataType: "html",
success: function (data) {
$("#ratingModal").find(".modal-body").html(data);
}
});
});
$("#ratingModal").on("hide.bs.modal", function (e) {
$(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');
return false;
}
By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);
Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.
Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
....
url = .....
}
$(function() {
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
});
However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);
In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
//retrieve the url from the modal
var url = $(this).data('table-url');
//use the url
$.ajax({ url: url, .... }):
});
Related
I have a table with data and a function to help me get values from rows:
function getRow () {
$('#mytable').find('tr').click( function(){
let fname = $(this).find('td:eq(4)').text();
let start = $(this).find('td:eq(5)').text();
let end = $(this).find('td:eq(6)').text();
.......ajax method () etc
................
}
So far, it has been working perfectly and fetching me the correct data. I had another function elsewhere in the page, where clicking on some links would fetch some data from the server and reload the page to display the new data. Everything was working like clockwork.
Now, I decided that when re-displaying fresh data, instead of reloading the page, it's better to refresh the #mytable div. Indeed, it worked, but alas it spoiled the first function. So basically the function below has introduced a bug elsewhere in the page, and I'm not sure why or how to fix it. It's as if the div refresh has completely disabled the event handler. Any ideas?
$(document).ready(function() {
$(".key").click(function(event) {
event.preventDefault();
var word = event.target.innerHTML;
$.ajax({
url: '.../',
data: {
action : "key",
keyword: word
},
type: 'get',
success: function(data){
$('#mytable').load("/.../../..." + ' #ytable');
},
error: function(e){
console.log(e);}
});
});
});
I have the following script I've written.
<script>
$(document).ready(function(){
$('a').data('loop',true);
$('body').on('click', 'a', function(event){
console.log($(this).data('loop'));
if ($(this).data('loop') == 'true') {
console.log('hit');
event.preventDefault();
caller = $(this);
$(this).data('loop',false);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
$(caller).click();
}
});
} else {
console.log(event.isDefaultPrevented());
console.log('miss');
$(this).data('loop',true);
}
});
});
</script>
It works, sends me the details I want etc etc. BUT!!!
When I click a link, It fires off the details to me via Ajax, then it's meant to "click" the event again, which it does! but the event does not fire it's normal action. So When clicking a link to another page, I would go to that other page... that's not happening.
If I comment out the line event.preventDefault(); Then the event fires as I would expect...
So to me it looks like the event.preventDefault is executing even though it's not meant to be during the second call...
Sorry if this is a bit complicated to understand. I don't quite understand what's happening myself.
Is it possibly a bug, or is there something that I've done that has caused this?
I didn't think I could, but I have successfully made a jsfiddle for this.
https://jsfiddle.net/atg5m6ym/2001/
You can try this and not worry about the "loop" anymore:
$(document).ready(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
window.location.href = linkref; // Redirect happens here
}
});
});
});
UPDATE
There's a few issues to note here:
1) Some links don't require a redirect (as noted, bootstrap model links that control showing/hiding or within document anchors
To correct this it really depends on the case. Usually bootstrap adds specific classes or data attributes to the links so you can do something like.
$('body').on('click', 'a:not(list of things to exclude)'..
Personally I'd instead define the links I wanted to track as :
<a href=<link> data-tracked='true'...
<script>
$('body').on("click","a[data-tracked='true']"...
Or if you want to track most links with a few exceptions you can:
<a href=<link> data-tracked='false'...
<script>
$('body').on("click","a:not([data-tracked='false'])"...
Or more generally:
<script>
$('body').on("click","a", function () {
if ($(this).attr("data-tracked") == "false" || <you can check more things here>){
return true; //Click passes through
}
//Rest of the tracking code here
});
The following if statement will return true whenever the data-loop attribute exists against an element, regardless of it's value:
if ($(this).data('loop')) {
It needs to be changed to check for the value:
if ($(this).data('loop') == 'true') {
When you assign anything to be the value of an element attribute it becomes a string and, as such, requires a string comparison.
Event.preventDefault() is not being executed second time.
Link redirection happens when the method is completed.
So in your case redirection will happen when complete method of ajax call is completed.
lets say, we have event1 and event2 object in the code. event1 is the object in the ajax call method and event2 is the event object in recursive call (second call) method.
so when link is clicked second time , we still have complete method to be executed. as soon as it returns to the complete method of ajax call, it finds the event1 is having preventDefault property true and it does not redirect.
Try this ;)
$(document).ready(function(){
$('body').on('click', 'a', function(event){
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({
linkref: linkref,
linkpos: linkpos,
screenwidth: screenwidth
});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
/* To temprary block browser; */
async: false,
data: "json=" + json_data,
complete: function(jqXHR, status){
/* add class **ignore** to a element you don't want to redirect anywhere(tabs, modals, dropdowns, etc); */
if(!caller.hasClass('ignore')){
/* Redirect happens here */
window.location.href = linkref;
}
}
});
});
});
There are links to various articles on my Webpage that open an article in a Bootstrap modal. Inside the body of Modal there are two links, one to previous article and other to next article. As of now, when a user clicks on any of these links inside of showing the content inside the modal, the link loads in the browser itself. Here is what my modal function looks like :
function openModal() {
// Store vallues in variables: var url , urlSplit, mainPage, txt, content
// prevLink, nextLink, imageURL etc.
// All of them have correct values.
$.ajax({
type: "POST",
url: 'getarticle.php',
data: {
link: url,
page: mainPage
},
success: function(data) {
var moreLinks = '<a class="modal-link" href="'+nextLink+'">Next</a>';
data = data+moreLinks;
$('.feed-modal .modal-body').html(data);
$('.progress').fadeOut();
}
});
}
The openModal function is triggered by :
$('a.modal-link').on('click', openModal);
So, a click on moreLinks should change the text inside the Modal but it instead loads the link in browser. How can I just load the content in Modal?
as the link is dynamically added to the DOM, you need to use event delegation:-
$('.feed-modal').on('click', 'a.modal-link', openModal);
and add event to openModal() so you can event.preventDefault(); to stop the a's default behaviour in loading in the browser:-
function openModal(event) {
event.preventDefault()
You need to set an onclick handler on the link inside modal.
// Event delegation approach as the link are genrated dynamically.
$(document).on("click", ".modal-link", function(e) {
e.preventDefault(); // Prevent redirection on button click
$('.progress').fadeIn(); // Fadein the progress
var url = this.href;
var mainPage = ""; // Set it to something , i dont know what it is.
$.ajax({
type: "POST",
url: 'getarticle.php',
data: {
link: url,
page: mainPage
},
success: function(data) {
// Rest all code to update the content is same.
var moreLinks = '<a class="modal-link" href="' + nextLink + '">Next</a>';
data = data + moreLinks;
$('.feed-modal .modal-body').html(data);
$('.progress').fadeOut();
}
});
});
I have a list in HTML which looks like
<a onclick="open_file()" id="3.txt">3.txt</a>
My open_file() function is looking this
function open_file() {
$("a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
}
The problem is function finally loads data into all fields(text_form and f_name) only after two clicks on such link. It works even if I at first click on one file, then click on another and it loads. Is there any way to fix this?
What you're currently doing is adding an onclick event to a link that calls a function that adds another onclick event via jQuery.
Remove the onclick property and the open_file() function wrapper so that jQuery adds the event as you intended.
You do not need onclick="open_file()" this:
<div id='linkstofiles'>
<a id="3.txt">3.txt</a>
//other links go here
</div>
$("#linkstofiles a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
You don't need to bind a click event again in the function when you have onclick in your html.
Also for $ is not defined, you need to put jquery library in the head.
Hi I asked before on how to load a div's content (A url) by clicking a button and not on page load before and I got this code as an answer:
<script type="text/javascript">
function toggleDiv(id){
if ($('#' + id).html() == '') {
$.ajax({
url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success: function(data) {
$('#' + id).html(data);
},
error: function() {
$('#' + id).html('The resource could not be loaded');
}
});
}
$('#' + id).toggle(); // Toggle div visibility
}
</script>
Show/Hide Value
<div id="a" style="display:none"></div>
First of all it doesn't work correctly and always show "The resource could not be loaded" if you put a txt link like (http://knowpersia.com/a.txt) it doesn't work either.
Secondly the Show/Hide Value link uses a href=# and onclick system to work. When I use it on my website it gets back to the homepage when I click it. Is there a way to change it to something like:
Show/Hide Value
Thanks
You have to pass an id to the toggleDiv() function, and you're passing a collection of objects -> toggleDiv('a') // Nop.
Also, if you're using jQuery, I suggest you get rid of that ugly inline code. Then, you can pass jQuery objects into your function:
Show/Hide Value
<div id="content"></div>
.
var toggleDiv = function($el) {
if ($el.empty()) { // You can just use `empty()`
$.ajax({
url : 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success : function (data) {
$el.html(data);
},
error : function () {
$el.html('The resource could not be loaded');
}
});
}
$el.toggle(); // Toggle div visibility
};
$('#link').click(function(){ toggleDiv($('#content')); });