I am trying to add javascript to my page after ajax call as I have newly created elements from the ajax response and I want them to listen to the javascript. Eveything works okay.
However,for some reason, I want to block that JavaScript functionality at some later point in time.
I have tried removing the script tag from the html using Javascript but it's not being effective. I have even tried using libraries such as
YETT but still i am not able to block the script I intend to block.
Javascript code
<script>
$(document).ready(()=>{
//when the page first loads I append the script (NOTE:I have this inside an ajax call as I am
appending html elements from the ajax call response
const scriptsrc = document.createElement('script')
scriptsrc.setAttribute('type','text/javascript')
scriptsrc.setAttribute('src','./assests/scripts/script.js_r='+Math.random()+Math.pow(10,10).toString(2))
scriptsrc.setAttribute('data-name','myscript')
$('head').append(scriptsrc)
//i do some other stuff here
//I want to block the script that i previously added (./assests/scripts/script.js) below here
})
</script>
Related
I have multiple pages that loads inside an div while navigate, the script written inside page 1 overlaps with the script written in page 2. Likewise the script that loaded in previous page also loads in the current page. I use load() to load an html page
i have tried remove(), off(click) but not succeed
$(document).off('click','.areaClk');
$(document).on('click','.areaClk',function(){
$(this).addClass('keyenable');
});
code in page 1 should not works in page2
well,you can use "window.location.pathname" to get the current webpage url on which your script is applying.If you dont want your script to apply for a specific page you can do something like below
//here give url where you want your script to apply
if (window.location.pathname == "localhost/mysite/page1")
{
// add script that you want to execute only for specific page
alert("applying only for page 1");
}
Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}
I started a new custom template for safari in dashcode ("This template creates a blank web application, ready for customizing."). It auto generates a function load in main.js that is called from the body in index.html:
function load() {
dashcode.setupParts();
}
I added some JS code after the function which seems to execute as part of the HEAD when i run. I also added an onclick event in the body of index.html:
<body onload="load()";>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
I also got the the button for it when I run.
Whenever I add a document.write call to the function load (which should just execute on load before the button is displayed) nothing else gets generated when I run. In other words whenever load becomes:
function load() {
dashcode.setupParts();
document.write("LOADING");
}
none of the javascript that i added after the function gets displayed. Also the onclick button that i added in the body doesn't appear.
Does anybody have an explanation for this behavior?
calling document.write() after page load will overwrite the current page - javascript, html, everything - which is why it is so frowned upon generally. Look at DOM methods or innerHTML manipulation for alternatives.
I am creating a chat system and I am using html/php/jquery.
How can I append a child with data from an external file to a div using javascript auto refresh feature?
The code that I have:
<script>
var auto_refresh = setInterval(
function()
{
$('#messages_box').load('refresh_messages.php');
}, 1000);
</script>
The code above refreshes the whole DIV with data grabbed from the mentioned document.
<script>
var auto_refresh = setInterval(
function()
{
var textnode=document.createTextNode("Water");
document.getElementById("messages_box").appendChild(textnode);
}, 1000);
</script>
And the code above, appends the text to the div I want.
I want to "combine" this two and obtain the following result:
Auto-refresh an external php file every second and if there are new results (messages in my case) the messages_box DIV should be updated with the results using the appendchils JS method.
I want to create a chat messaging system that will grab messages if a new result is encountered when loading the external php fild. I want to use the appendchild method, because by doing this I will practically add a new child to the div, not refresh the whole div. I absolutely need to append stuff, not to load the whole DIV again.
It seems to me that what you are looking for is an AJAX request.
Here's how I would set this up:
Have a database set up to store messages
Have a PHP file with various functions to both retrieve and send messages to/from the database.
Have another PHP/HTML file with javascript that creates an AJAX request to the other PHP file on a regular basis.
There is tons of documentation on how to create ajax requests with pure javascript, but I personally prefer to used the jQuery .ajax() function.
Currently I am using jQuery to choose what my index page should load depending whether a cookie is set.
For example, the body tag of the index.html should load hasCookie.html if the cookie is set and noCookieSet.html if no cookie is set.
My index page currently has:
load user scripts
load styling scripts
<html><body></body></html>
The user script has the code that checks whether the cookie is set. If it is, I use jQuery's load to load the content into the body:
$(document.body).load('hasCookie.html')
However, since this is executed asynchronously, the styling scripts have loaded before the body tag has been updated, hence the body is not styled.
Is there a way of having a synchronous load, or should am I approaching this in the wrong way?
EDIT: if it helps, the styling scripts are basically jQueryUI
AFAIK, JQuery load cannot be synchronous.
You can cet around this witha callback function.
$(document.body).load('hasCookie.html', function(){
//call styling script here
});
In your case, this sounds like it would really be a better idea to implement server-side if possible. In PHP it would be a simple matter of detecting if the cookie you want is set in the $_COOKIE array and outputting the correct page.
You can form it as an AJAX request and populate your page with the response. Set the async option to false. This SO answer has more: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
Just change document.location.href to the url of the page.
What you're doing is loading content with ajax and placing it within the page body. You'd do this if you didn't want any resources declared in head to get requested. But there's no point in that since you can do it with caching.
Try
$(document).ready(function() { $(document.body).load('hasCookie.html'); });
This will postpone loading until after everything else is already there.
This is how i do it.
You can attach Style and Javascript upon callback from the Ajax Function.
$.ajax({
url: somePage,
success:function(ajaxData){
//ATTACH AND RUN CORRESPONDING PAGE SCRIPT
var script = somePage + '.js';
$.getScript(script);
//ATTACH CORRESPONDING STYLE SHEET
var style = document.createElement('link');
style.type = 'text/css';
style.href = '/css/'+somePage+'.css';
style.rel = 'stylesheet';
style.media = 'screen';
document.getElementsByTagName('head')[0].appendChild(style);
//ADD HTML RETURNED
$('body').html(ajaxData);
});
This allows everything to be loaded including styles and javascript, given that the script name and css file name are the same.