Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i am creating simple Vue.js application i am using Vue cli 3, I want to use native DOM method, to watch scroll behavior, Everything works fine, but the problem occurs when i am changing router view, and then console throws error Uncaught TypeError: Cannot read property of undefined what i am doing wrong?
created() {
/* contorl slider scroll height and give navbar fixed positiom */
window.addEventListener("scroll", ()=>{
var firstbox = document.getElementById("sliderBox");
if (window.scrollY >= firstbox.scrollHeight) {
this.isVisiable = true
} else {
this.isVisiable = false
}
});
},
To be a honest, I could not understand exactly what your problem is, but i think you are using addEventListener not right way, if you want to use it in created() hook also you need to destroy it after route changed, in Vue2 you can use destroyed() hook, but in Vue3 you can use unmounted(), hope this will help you
methods:{
yourFunction() {
var firstbox = document.getElementById("sliderBox");
if (window.scrollY >= firstbox.scrollHeight) {
//do something
} else {
//do something
}
}
}
created() {
window.addEventListener("scroll", this.yourFunction);
},
unmounted(){
window.removeEventListener("scroll", this.yourFunction)
}
.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a on click function which return 'x' and stores in div dynamically. After a page refresh, this dynamic div resets and the data is gone. But i want the data to stay. To do that i stored that in local storage and want to call later when page loads. I store it in local storage inside the function 'test'
and calling it in windows.onload which is returning null. I understand that i am unable to call the local storage inside the function. My question: Is there a way to call the local storage inside the function 'test'
function test(parameter1, parameter2) { // this is an onclick function
// some functionality
return x;
var test = x.innerHTML;
localStorage.setItem('somediv', test);
}
window.onload = function () {
var test2 = localStorage.getItem('somediv')
$('div.somediv').text(test2);
}
You are using localStorage fine.
The thing is, if you return x; in your text() function, the code below is never executed, so it never actually sets the localStorage variable.
That is why you get null when you are trying to access it.
Try this, you will get an idea.
Click me
<script>
function test(param) { // this is an onclick function
localStorage.setItem('somediv', param);
alert('ok');
}
window.onload = function () {
if(localStorage.getItem('somediv')==null){
return;
}
var test2 = localStorage.getItem('somediv')
//$('div.somediv').text(test2);
alert(test2);
}
</script>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a scripts file which I use for click events that trigger axios or Ajax requests but in some views that button doesn't exist and there is an error in console that says:
Uncaught TypeError: Cannot read property 'addEventListener' of null
How can I prevent this? Do I have to wrap it in an if statement or surely there is a more elegant way?
document.querySelector(".book-now").addEventListener("click", e => {
// declare variables
// send Ajax request
// etc.
You could use a delegate listener instead:
document.addEventListener('click', e => {
if (e.target.matches('.book-now') {
// declare variables
// send Ajax request
// etc.
}
})
If you don't want that (or have to listen to an event that won't bubble) your only option is to check whether the element exists:
let bookNowBtn = document.querySelector(".book-now");
if (bookNowBtn) {
bookNowBtn.addEventListener('click', e => { /*...*/ })
}
You can first check if the element exist
let elem = document.querySelector(".book-now");
if (elem !== null) {
elem.addEventListener("click", e => {
//rest of the code
})
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i am not quite sure that Title related to my problem, so sorry.
I have asynchronous function that call callback function. So the main idea is I want to call function "dodo" each time after "asyncFunc" is done.
Are there some patterns for that? Are there issues releated to memory leak ?
var can = true;
function dodo() {
if(can)
{
can = false;
asyncFunc(function(data) {
doSmth();
can = true;
});
}
}
setInterval(dodo, 0);
The main idea is I want to call function "dodo" each time after "asyncFunc" is done.
So just call it there:
function dodoForever() {
asyncFunc(function(data) {
doSmth();
dodoForever(); // <==
});
}
dodoForever();
You don't need a global can state and setInterval.
You can just call it. Like so.
var can = true;
function dodo() {
if(can)
{
can = false;
asyncFunc(function(data) {
dodo(); // this will run `dodo` function again.
doSmth();
can = true;
});
}
}
setInterval(dodo, 0);
As the comments mention this will blow the stack up. You have dodo running every 0ms. This will basically call dodo a TON of times and that is basically all your program will be doing. I can't think of a use case where this would be necessary and it probably won't fair so well in terms of performance.
Really think about why you are trying to run it like that and what the end goal is.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
While getting used to the concept of promises I have been wondering if elements like HTMLImageElement will have a native promise in future for a 'load' success or failure, similar to the 'load' event which already exists, but with the advantages of being able to be polled after loading?
https://www.w3.org/2001/tag/doc/promises-guide#one-time-events
Promises are definitly a good idea. The problem however is that the DOM has an event model and events and Promises don't really work well together. You can't have a promise for an onclick event for instance (well, you can, but what does it mean?) Some events, like load, may seem to make sense but what if you change the src? You'll get another load event!
Maybe someone is going to have a good idea how to unify these concepts. For now, I think we're stuck with writing code that interfaces between events and Promises.
Not as of HTML5. But I like the concept. I would love to see promise-events in HTML6.
The document you referenced is a guide for when to use promises. So, if you are creating a custom object with events, you might consider implementing a promise interface for your one-time events.
You could easily implement a library to add promise events to DOM elements today.
function loadPromise(image) {
if (image.src && image.complete) {
if (image.naturalWidth > 0) {
return Promise.resolve(image);
}
else {
return Promise.reject(new Error("image failed loading"));
}
}
return new Promise(function(resolve, reject) {
image.addEventListener("load", function(e) {
resolve(image);
}, false);
image.addEventListener("error", function(e) {
reject(new Error("image failed loading"));
}, false);
if (image.src) {
// IE reports image.complete as false when there is an error
var errTest = new Image();
errTest.onerror = function(e) {
reject(new Error("image failed loading"));
};
errTest.src = image.src;
}
});
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using onclick for an element, but need to pass a callback to it like this:
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
do something
if (cb != undefined)
cb();
}
onclick="javascript:foobar(1, cb_func)"
foobar gets called, but my cb_func isn't - in fact when I step in to cb() usinf Firebug, it shows me the HTML for the entire page.
Any ideas how I might achieve this?
Use event delegation:
$(document).on('click', '.dynamicGeneratedEl', function(event){
// do something
cb_func();
});
Where .dynamicGeneratedEl is a suitable selector for your case.
comment the line // do something
function cb_func() {
alert("hello world!");
}
function foobar(i, cb) {
// do something
if (cb != undefined)
cb();
}
Try this:
https://jsfiddle.net/h3ckcgvv/2/
var nextFunction = function() {
// some more stuff happens
}
var processClick = function() {
// some stuff happens
// condition
nextFunction();
}
$('.js-click-me').click(processClick);
The condition could be anything, based on page inspection, javascript variable state, data attributes on the clicked HTML element etc. Much more stable and maintainable than onclick attributes and hardcoding the callback into every call where it's needed.