Dynamic content is not displayed on page reload - javascript

After my page is loaded, I run a script where I dynamically add click event to my hidden button, and trigger the click. This way I am forcing a javascript library to reload every time a reload a page.
Then this library makes request, and response is being displayed in appropriate manner.
First time I load the page, the response is displayed (selected text is highlighted). Every next time, library is reloaded, but response is not displayed. I want to make it displayed every time I reload the page.
I have tried to disable cache, refresh it with shift+f5, but still no success.
This is my code:
<body>
<div id="content">
<div id="pdfContainer" class = "pdf-content">
</div>
</div>
<input id="btn" type="button" hidden="true" />
<script>
function loadAnnotator() {
var content = $('#content').annotator();
console.log("Annotator loaded");
};
$(window).load(function () {
var btn = $("#btn");
if(btn !== null && btn !== undefined) {
btn.on('click', loadAnnotator);
btn.click();
}
});
</script>
</body>
I can make it work with displaying and manually clicking this button, but that is not the desired behavior.
How can I make it work the way I desire? Thank you in advance.

Instead of the whole hack, try this oneliner instead:
$($('#content').annotator));
There's no need for the hidden button. If this doesn't work there's a chance 'annotator' isn't initialised until after this script.

The problem is with the btn.click(); this doesn't work in some browsers!
JavaScript to rescue like this btn[0].click(); or you need to change your logic as follows
<body>
<div id="content">
<div id="pdfContainer" class = "pdf-content">
</div>
</div>
<input id="btn" type="button" hidden="true" />
<script>
var content =null;
function loadAnnotator() {
if(content==null)content =$('#content').annotator();
console.log("Annotator loaded");
};
function clickedButton(){
loadAnnotator();
}
$(window).onLoad(function () {
var btn = $("#btn");
if(btn !== null && btn !== undefined) {
btn.on('click', clickedButton);
clickedButton();
}
});
</script>
</body>

Solved: I have added a timer and forced the button to be clicked after 300ms.
Somehow like this:
<body>
<div id="content">
<div id="pdfContainer" class = "pdf-content">
</div>
</div>
<input id="btn" type="button" hidden="true" onclick="loadAnnotator()" />
<script>
var content = null;
function loadAnnotator() {
if (content === null) {
content = $('#content').annotator();
}
console.log("Annotator loaded");
}
;
function clickedButton() {
var btn = $("#btn")[0];
if (btn !== null && btn !== undefined) {
btn.click();
console.log("Button is clicked");
}
}
$(window).load(function () {
setTimeout(clickedButton, 300);
});
</script>
</body>
Also, I've listened to suggestions as
var btn = $("#btn")[0];
Sometimes, one forgets about such fundamental things about jQuery :)
If I add time less then 300ms, it is behaving the way I mentioned above.
Thank you, all of you!

Related

How to hide div after page refresh or click browser back button

I have popup code below and I want to show this popup for per-user, only one time even with a page refresh or visiting another site.
I tried some code but it isn't working for me.
<div id="popup">
<div id="close">×</div>
MY CONTENT
</div>
<script type="text/javascript">
window.addEventListener("load", function(){
setTimeout(
function open(event){
document.querySelector("#popup").style.display = "block";
},
0000
)
});
document.querySelector("#close").addEventListener("click", function(){
document.querySelector(".popup").style.display = "none";
});
</script>
I think using localstorage will do the trick. It won't work here cause stack doesn't allow localstorage
if(localStorage.getItem('closeMe') == 'yes')document.getElementById("popup").classList.add("closeMe");
document.querySelector("#close").addEventListener("click", function(){
localStorage.setItem('closeMe', 'yes');
if(localStorage.getItem('closeMe') == 'yes')document.getElementById("popup").classList.add("closeMe");
});
.closeMe{
display:none;
}
<div id="popup">
<div id="close">×</div>
MY CONTENT
</div>
Use a cookie to remember.
window.addEventListener("load", function(){
//check if cookie exists.
if (!document.cookie.includes("popup")) {
setTimeout(
function open(event){
document.querySelector("#popup").style.display = "block";
//set cookie since it didn't exist previously
document.cookie = "popup=true"
},
0000
})
});
document.querySelector("#close").addEventListener("click", function(){
document.querySelector(".popup").style.display = "none";
});

Is there a race condition to remove the elements?

I'm very new to JS and HTML. I would like to remove an element from the page as soon as the page is loaded. This is my simple HTML code:
<html>
<head>
</head>
<body>
<div id="trapParent"><a id="trap" href='/trap/removeByJS'> Javascript removal </a></div>
<script>
function timeout() {
setTimeout(function () {
timeout();
}, 1000);
}
timeout();
var parent = document.getElementById('trapParent');
var child = document.getElementById('trap');
while (child & parent){
parent.removeChild(child);
parent = undefined;
child = undefined;
}
</script>
</body>
</html>
But when I open the page I can still get a reference to the link on the page; when I get the value of document.getElementById('trap');, it returns the link which means that it is still in the DOM and I can see that the link is still there. Am I missing something here?
I added the timeout function to make sure that the script will run after the page is loaded.
Thanks to above answers, the following worked for me:
<html>
<head>
</head>
<body onload = "removelink();">
<div id="trapParent"><a id="trap" href='/trap/removeByJS'> disables Javascript </a></div>
Hey!
<script>
function removelink( ){
var parent = document.getElementById('trapParent');
var child = document.getElementById('trap');
while (child && parent){
parent.removeChild(child);
parent = undefined;
child = undefined;
}
}
</script>
</body>
</html>

Uncaught ReferenceError: function is not defined

I try to display a popup when I click on a button using javascript.
But this error appears :
Uncaught ReferenceError: confirmation is not defined
at HTMLButtonElement.onclick
function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer) {
alert("Bye bye!")
window.location = "http://www.google.com/";
} else {
alert("Thanks for sticking around!")
}
}
<button type="submit" class="danger btn btn-danger" onclick="confirmation()">Transférer</button>
I suggest a solution that will work for sure.
Add an event listener of DOMContentLoaded to the whole document and call an anonymous function.
You can then wrap your code in that function's brackets
and it will execute once loading is complete.
<button type="submit" class="danger btn btn-danger" >Transférer</button>
<script>
var btn = document.querySelectorAll("button")
document.addEventListener('DOMContentLoaded', function () {
btn[0].addEventListener("click", function () {
// When this button is clicked we want to enable zooming of our list.
// To do this we add an event listener to our list itself,
// so when the cursor hovers it, the enlarge function gets called.
var answer = confirm("Leave tizag.com?")
if (answer) {
alert("Bye bye!")
window.location = "http://www.google.com/";
} else {
alert("Thanks for sticking around!")
}
});
});
</script>
have a good day :)
You may haven't linked your .js file with your .html file. That's the only possible problem.
At the end of your html <body> tag add a:
<script src="your-script.js" type="text/javascript"></script>
Did you place your javascript code to a script block? i.e
<script type="text/javascript">
function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer) {
alert("Bye bye!")
window.location = "http://www.google.com/";
} else {
alert("Thanks for sticking around!")
}
}
</script>
<button type="submit" class="danger btn btn-danger" onclick="confirmation()">Transférer</button>

Page re-load on AJAX return looses focus on button

I have a button click action upon which I make AJAX call to update a field. After the AJAx returns, I am doing this -
document.location.reload(true);
The page reloads, however, the focus is not returning to the button. Can you suggest a means where I can reload/refresh the page and the focus returns on the button to click again?
I have updated my AJAX code here, please tell me how to modify this -
<input type="button" name="IncreaseMyDate" id="myDate" value="Increase" onclick="updateMyDate('<%=myDate%>')"/>
function updateMyDate(mywDate)
{
XMLHttpObj_myDate = CreateHttpObject();
if(XMLHttpObj_myDate == null){
alert("HTTP Request not supported");
return;
}
var itemId = document.getElementById("itemId").value;
document.getElementById("myDate").setAttribute("disabled",true) ;
var url ="IncreaseMyDate.jsp?action=update&myDate="+reviewDate;
document.getElementById("myDate").style.cursor = "not-allowed";
XMLHttpObj_myDate.onreadystatechange=fillMyDate;
XMLHttpObj_myDate.open("GET",url);
XMLHttpObj_myDate.send(null);
return false;
}
function fillMyDate(){
if(XMLHttpObj_reviewDate.readyState == 4 || XMLHttpObj_myDate.readyState == "complete"){
document.getElementById("myDate").style.cursor = "pointer";
document.getElementById(myDate").innerHTML = XMLHttpObj_myDate.responseText;
document.location.reload(true);
}
}
Why do you do the page reload? The big advantage of making Ajax calls is that they avoid the need to reload the page. You could just do all the Ajax work server-side when you are reloading the page.
You need to pass a variable to the new page load that indicates what button should have the focus. Your page reload doesn't know about what was happening client-side before. Pass the id of the button in the query string and then use it to find the button again and set the focus.
You could store the button's id in sessionStorage, and then check when the page loads to reapply the focus if applicable.
The following page worked in my tests:
<body onload="body_onload();">
<button id="buttonA" onclick="button_click(this);">Button A</button><br/>
<button id="buttonB" onclick="button_click(this);">Button B</button><br/>
<button id="buttonC" onclick="button_click(this);">Button C</button><br/>
</body>
<script>
function body_onload() {
var buttonId = sessionStorage["buttonId"];
if (buttonId) {
document.getElementById(buttonId).focus();
}
}
function button_click(button) {
sessionStorage["buttonId"] = button.id;
document.location.reload(true);
}
</script>

How to give option to recall function using javascript after running on load

I want to automatically run a function upon loading the webpage, and then I want to give the option to rerun the function after it's executed.
The following code will work if I the part is not in the database, and will work if instead of using document.write is use alert for displaying the part, but if I use document.write, the button to search again disappears. I think it's because the buttons aren't being re-initialized. I've moved that around and gotten nothing, and tried reloading the webpage, which is functional, but unsatisfactory because of the time it takes.
Is there anyway to prevent the buttons from disappearing, or a better method you recommend?
Thanks in advance.
<!DOCTYPE HTML>
<html>
<body>
<input id="clickMe" type="button" value="Search for Another Part" onclick="search_part();" />
<script type="text/javascript">
function search_part()
{
var part = prompt("Stackoverflow example: ");
if( typeof part === 'undefined' )
{
alert("That part is not in the database.")
}
else
{
document.write( part )
}
}
window.onload = search_part();
document.getElementById("Button").onclick = search_part;
</script>
After DOM is loaded, document.write replaces all content on page. Instead you probably want to have a element container on body and display messages in that.
<input id="clickMe" type="button" value="Search for Another Part">
<div id="messages-here"></div>
<script type="text/javascript">
function search_part () {
var part = prompt("Stackoverflow example: ");
if (typeof part === 'undefined') {
alert("That part is not in the database.");
} else {
document.getElementById('messages-here').innerHTML = part;
}
}
window.onload = search_part();
document.getElementById("clickMe").onclick = search_part;
</script>

Categories