I am trying to build a site that dynamically loads the pages. Certain pages have extra javascript that they load. I need to be able to unload this javascript when the page changes. Is that possible? My code so far (work in progress still):
//When page loads...
$("ul.toggle li:first").addClass("active").show(); //Activate first tab
var taburl = $("ul.toggle li:first a").attr("href").substr(1);
$(document).ready(function(e) {
$.ajax({
type: "POST",
url: taburl+'.php',
data: '',
dataType: "html",
success: function(d){
$('#main').html(d);
}
});
});
//On Click Event
$("ul.toggle li").click(function() {
$("ul.toggle li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$("#main").fadeOut(500);
$("#main").html('');
var activeTab = $(this).find("a").attr("href").substr(1) + '.php'; //Find the href attribute value to identify the active tab + content
$("#main").load(activeTab).fadeIn(500); //Fade in the active ID content
});
Let me know if any other info is needed.
Related
As we know that react doesn't load the window on click of an anchor. That's why react web apps are fast. I want the same functionality in jQuery. I want to Load a page in Jquery Without Loading the head, header, and footer. How can I do it? I don't know if I can even do it or not.
$(document).on("click", function (e) {
let anchor = $(e.target);
var url = anchor.attr("data-url-redirect");
if (e.target.nodeName == "A") {
// console.log(anchor, url);
$.ajax({
url: url + '.html',
success: function (result) {
$(".pageWrapper").html(result);
console.log(result, url);
if (history.pushState) {
var newurl =
window.location.protocol +
`//` +
window.location.host +
window.location.pathname +
"/" +
url;
window.history.pushState({ path: newurl }, "", newurl);
}
},
});
}
});
});
This is the code I wrote. I can load the page and change the URL. But when I refresh the page breaks. Please let me know if it is possible with jQuery or not. If it is possible then how can I achieve it?
I have a function that records clicks on a link with a data tag. The code hides a telephone number until the link has been clicked, then it reveals the number. The problem I'm having is I am unable to get that revealed number to fire without user interaction once it has loaded.
I had to prevent the default event for when the button is clicked for the first time as the url does not yet contain the real data and also I don't want the page to jump.
Once clicked the new link's html will change to, example: "☎ 0123456789"
and the href will change to, example: "tel:0123456789"
This data is obtained from JSON sent from AJAX PHP file.
After this I want to programatically click the URL but I can't seem to get it to fire and keep getting a console error message saying "Uncaught TypeError: event is undefined" ~ presumably to do with the event prevent default?
Info: there will be multiple phone numbers loaded via PHP so I need to access each one individually.
HTML for the link;
<a data-num='$number' class='telephone' href='#'>☎ Click to call</a>
JS code (jQuery 3.4.1);
$(document).on('click','.telephone',function(event) {
event.preventDefault(); // Prevent page jump
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']); // True or false
var c = (a[0]['tel']); // Number or error
// If result found change URL and click it to call number
if (b == true) {
$('.telephone[data-num="' + num + '"]').html("☎ " + c); // Change link text
$('.telephone[data-num="' + num + '"]').attr("href", "tel:" + c); // Change link href
$('.telephone[data-num="' + num +'"]').click(); // Update: This causes a loop because it runs the code again. I need to hide the original a tag and create a new one then trigger it.
}
}
});
});
Any suggestions?
Calling the .click() method doesn't create an event. The event is created when the user actually clicks something. If you console.log(event) it'll be undefined when called by .click(), which is where you're getting the error from. To get around that you could
if (event) { event.preventDefault(); }
But then you're going to run into recursion since you're basically
$(document).on('click', '.telephone', function() { $('.telephone').click(); });
To get around that you could add something like a loaded class
$(document).on('click', '.telephone:not(.loaded)', function() {
$('.telephone[data-num="' + num +'"]')
.addClass('loaded')
.attr(...)
.html(...)
.click();
});
Also, you'll thank yourself later for using a little more descriptive variable names. And for those unaware, jquery is chainable.
Figured it out. I was creating a loop so the click wouldn't work so I hid the first link after the click and loaded a new hidden one. I used a different column value from the table for the data tag on this new link to avoid any possible conflicts.
Apart from the loop issue the major part I was missing was [0] before assigning .click.
Thanks for the suggestions along the way.
Working code below;
$(document).on('click', '.telephone', function(event) {
event.preventDefault();
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']);
var c = (a[0]['id']);
var d = (a[0]['tel']);
if (b == true) {
$('.telephone[data-num="' + num + '"]').hide(200);
$(document).ready(function() {
$(".telephone-reveal");
$('.telephone-reveal[data-id="' + c + '"]').show(200);
$('.telephone-reveal[data-id="' + c + '"]').html("☎ " + d);
$('.telephone-reveal[data-id="' + c + '"]').attr("href", "tel:" + d);
$('.telephone-reveal[data-id="' + c + '"]')[0].click();
});
}
}
});
});
First, I have a list table in each row have button edit, if button edit click show modal1 where have detail from each row and have button to edit2, if button edit2 click will show modal2 after button save from modal2 been click how to refresh data in modal1
So far where all modal been close and modal1 open data have correct update, but I want just modal2 close and data in modal1 refresh without close all modal
This is my button save code function save1()
{
$('#btnSave1').text('saving...'); //change button text
$('#btnSave1').attr('disabled',true); //set button disable
var url;
if(save1_method == 'add1') {
url = "<?php echo site_url('person/ajax_add1')?>";
} else {
url = "<?php echo site_url('person/ajax_update1')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form1').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form3').modal('hide');
// $('#modal_form3').on('hidden.bs.modal', function () {
// window.alert('hidden event resfreh!');
// });
reload_table();
}
$('#btnSave1').text('save'); //change button text
$('#btnSave1').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave1').text('save'); //change button text
$('#btnSave1').attr('disabled',false); //set button enable
}
});
}
I'm trying to pass the active dom element when the contextmenu is clicked from my background script to a script that is being called through chrome.tabs.executeScript. I can pass booleans and strings just fine, but i always get an error when i pass dom elements. I'm starting to think it's not possible.
//doScripts function called from browser action
chrome.browserAction.onClicked.addListener(function(tab) {
doScripts(true, null);
});
//doScripts function called from context menu click
function getClickHandler(info, tab) {
var currTarg = document.activeElement;
console.log("currTarg = " + currTarg);
doScripts(false, currTarg);
}
//i reference doingBrowserAction and contextTarg in myscript.js
function doScripts(context, targ){
chrome.tabs.executeScript(null, {code: "var doingBrowserAction = "+context+"; var contextTarg = "+targ+";"}, function(){
chrome.tabs.executeScript(null, {file: "js/myscript.js"}, function(){
//all injected
});
});
}
//setup context menu
chrome.contextMenus.create({
"title" : "DESTROY!",
"type" : "normal",
"contexts" : ["page","selection","link","editable","image","video","audio"],
"onclick" : getClickHandler
});
i reference doingBrowserAction and contextTarg in myscript.js. I know what i'm trying to do is possible because the adblock extension does it, but having a hard time figuring out how. thanks in advance.
You cannot get a direct reference to a content script's DOM element from the background page, because the background page runs in the extension's process, and the content script runs in the tab's process. See also https://code.google.com/p/chromium/issues/detail?id=39507.
The document.activeElement property in the background page refers to the active element in the background page's document. As you can imagine, this value is quite useless.
If you query the state of the currently right-clicked element, bind an event in the content script. In the next example, I've chosen the contextmenu event, because context menus can also be opened through the keyboard.
This example adds a context menu option that removes the last active element from the document.
// content script
var lastElementContext;
document.addEventListener('contextmenu', function(event) {
lastElementContext = event.target;
}, true);
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (lastElementContext && lastElementContext.parentNode) {
lastElementContext.parentNode.removeChild(lastElementContext);
lastElementContext = null;
}
});
Background script:
chrome.contextMenus.create({
title: 'DESTROY!',
contexts: ['page', 'link', 'editable', 'image', 'video', 'audio'],
onclick: function(info, tab) {
chrome.tabs.sendMessage(tab.id, 'doDestroy');
}
});
I have a strange issue with my jquery mobile application. Below screen shot from Chrome Developer Tools Snapshot.
Why does my Pages or Scripts are cached even thiugh Have added
$.ajaxSetup ({
cache: false
});
Also in every ajax call which loads my ul > li have set cache:false.
Kindly let me know how can I overcome this scenario coz of this my Mobile cache is growing on every single click driving me nuts.
Thanks
Update :
Every time I click to navigate to another page this scripts get executed :
$('body').on('click', '.menuClass', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var menuid = $(this).attr('id');
if (menuid == '100001') {
settings.get('setval', function(obj) {
if(obj.value.tableMode == "1"){
$.mobile.changePage('categories.html', {
transition : "slide"
});
return false;
}
else{
$.mobile.changePage('index.html', {
transition : "slide"
});
}
});
}
});
But for somereasons the URL for categories.html loads on every click changing the url to
below
http://localhost:8080/categories?_=1347279588477
http://localhost:8080/categories?_=1347279584203
http://localhost:8080/categories?_=1347279688227
I don't know why cache:false doesn't work but i'm adding a time created string to prevent caching of ajax pages.
Doing this by adding &ts="+ new Date().getTime() to end of url .
Here is my usage ;
$.ajax({
type: "GET",
url: "ajax.php?ajax_file=ajax_table_page&ts="+ new Date().getTime(),
success: function(data){
..................
}
});
I also use this to trace ajax errors (you may add after document is ready )
$.ajaxSetup({
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});