Can't delete element with Javascript autorun at start - javascript

I was gonna simplify the page https://vio.edu.vn/arena (if you're asking) because I see elements that I didn't need was the element _3gMal. I usually like to code in 1 line so this is the code I use
function deleter() {
if (typeof document.getElementsByClassName('_3gMal')[1] == 'object') {
document.getElementsByClassName('_3gMal')[0].remove();
clearInterval(myInterval)
}
var myInterval = setInterval(deleter(), 1)
}
The code that I want it to do is delete the element _3gMal after it's visible but I think there's something wrong so it doesn't work properly. There's no error in the code.

Related

assigning anonymous functions to buttons

When i use if statements to determine whether a user has viewed the form before, it breaks my whole code.Originally, my code just removed a child, and set the display of the next DIV to "block".This worked perfectly fine. all my variables saved properly in the end, etc.
However, since I added these checks to the buttons, everything has gone haywire.
I've tried using different mixes of appendChild, removeChild, and style.display methods. I even booted it up in notepad++ to help me visualize.
document.getElementById("newUser").addEventListener("click", function(parent, start, personal){
parent.removeChild(start);
document.getElementById.style.display="block";
});
document.getElementById("toGeneral").addEventListener("click", function(){
if(reUser === 0){
oPersonal;
document.getElementById("general").style.display="block";
} else if(reUser === 1){
oPersonal;
parent.appendChild(oShowInfo);
} else {
window.alert("Whoops this function is in progress");
}
return oPersonal;
});
I want my forms to be editable at the end of the form.
In one test (not this one). I was able to move back and forth between pages, but it would stop the loops that kept my variables up.
This one is using the oldChild = parent.removeChild() method to fix that, which may also be part of the issue.
**Note: variables such as
oPersonal
reUser
parent
are stored just above this code at the beginning of the page loop.
New code:
document.getElementById("newUser").addEventListener("click", function(){
parent.removeChild(start);
document.getElementById.style.display="block";
});
document.getElementById("toGeneral").addEventListener("click", function(){
if(reUser === 0){
oPersonal;
document.getElementById("general").style.display="block";
} else if(reUser === 1){
oPersonal;
parent.appendChild(oShowInfo);
} else {
window.alert("Whoops this function is in progress");
}
return oPersonal;
});
You have many problems in this code. First, your click event's handler can not take 3 args like this. When an event is triggered, only this event is passed to the function. So your code should looks like :
document.getElementById("newUser").addEventListener("click", function(event) {
let element = event.target;
let parent = element.parentNode;
parent.removeChild(element);
//Next line is wrong since getElementById is a function and should take args
//document.getElementById.style.display="block";
});
Then on your second element's click event handler, it seems like you are trying to use parent which is not in the same scope.
Also the return statement is strange, what are you trying to do ?

Javascript/AJAX Asynchronous Loading Spinners

I am trying to make a basic enough page that allows the user to execute a php script by clicking a button. Each button will have a loading spinner popup on clicking.
My problem is, on clicking one button and then clicking another, both spinners close at the exact same time even though the second may still be processing.
Does anyone know how to make these spinners truly asynchronous ? Thanks so much in advance, its killing me.
JS:
function test(element){
var append = "#";
var test = append.concat(element);
document.getElementById(element).style.visibility='visible';
$.ajax({url:"test.php",success:function(result){
hide(element);
}
});
};
function hide(element){
document.getElementById(element).style.visibility='hidden';
};
</script>
HTML:
<html>
<?
$index = 0;
$myArray = array ("1", "2", "3", "4", "5");
for($index = 0; $index < 5; $index++){?>
<button onclick="test('<?echo $myArray [$index];?>')">Start</button>
<img id="<?echo $myArray [$index];?>" src="images/loader.gif"
style="visibility:hidden"/>
<br><br>
<?}?>
</html>
I would implement a counter. Each time you show the loading indicator, add one to the counter and each time you want to hide it, subtract one. Then monitor the counter and whenever it is above zero show the loading indicator and when at zero hide it. Make sense?
Something like the following (untested) code might do the trick and it neatly means you can avoid worrying about the spinner at all in ajax requests:
var spinningAjax = (function() { // use of the closure created by an immediate function gives us the scope to create a persistant counter variable
var counter = 0;
$(document).ajaxComplete(function() {
counter--;
if (counter === 0) {
showSpinner(false);
}
});
return function(settings) {
counter++;
showSpinner(true);
$.ajax(settings);
}
})();
var showSpinner(bool) {
// I'll leave this up to you as it looks like your posted html / js is for example purposes rather than replicating your actual site
};
EDIT: Ok, having seen the comments to another answer, I realise this doesn't quite solve the situation you're in. I'll have a think and see if I can do better
EDIT2: I think this (still untested, unfortunately) code may be what you require. Please let me know in the comments if you have any issues.
var spinningAjax = (function() { // closure of immediate function lets us create a persistant array of the counters for each spinner
var counter = []; // an array to hold the counters for each spinner
$(document).ajaxComplete(function(event, xhr, settings) { // called whenever any ajax request is completed
if (typeof settings.ajaxGroup !== 'undefined') { // only update the counters if an ajaxGroup has been provided
counter[settings.ajaxGroup]--;
if (counter[settings.ajaxGroup] === 0) {
showSpinner(false, settings.ajaxGroup); // hide spinner when all requests connected with the spinner have been completed
}
}
});
return function(settings) { // this is the function actually assigned to the variable spinningAjax as a result of the immediate function
counter[settings.ajaxGroup] = counter[settings.ajaxGroup] ? counter[settings.ajaxGroup]+1 : 1; // can't just use the ++ operator as this property might not be defined yet
showSpinner(true, settings.ajaxGroup);
$.ajax(settings);
}
})();
var showSpinner(bool, spinnerIdentifier) {
// I'll leave this up to you as it looks like your posted html / js is for example purposes rather than replicating your actual site
};

Can I run nest a $('element.class').each() function within the change() function for the same $('element.class')?

Specifically, I want to iterate over every element on the page, each time the value of one changes.
So to paraphrase my code I have:
$('select.filterbox').change(function() {
// stuff
$('select.filterbox').each(function() {
// other stuff
});
});
'stuff' all executes just fine, but 'other stuff' doesn't happen
Here's the full code
// On Filterbox Change
$j('select.filterbox').change(function() {
// Show All Rows
$j('#table1 tr').show();
// For Each Filterbox
$j('select.filterbox').each(function() {
var selVal = $j(this).attr('value');
var col = $j(this).closest('th').parent().children().index($j(this).closest('th'));
alert('Column '+val+' : '+selVal);
// If Selected Value Not Empty
if(selVal != "") {
// For Each Row
$j('#table1 tr').each(function() {
var $tds = $j(this).find('td');
var cellVal = $tds.eq(col).text();
cellVal = $j.trim(cellVal);
// If td text != selected
if( cellVal != selVal ) {
// Hide this row
$j(this).hide();
}
});
}
});
});
Answer: yes you can. I've done a lot of stuff like that recently. Indeed, your code should do it. It is likely that you've made some small but significant error in your code that will need to be hunted down and fixed. I've done a lot of stuff stuff like that recently, too.
More helpful answer: do things to figure out where the breakdown is. replace the "$('select.filterbox').each()" call with something obvious - say, calling .hide() on large chunks of your page. Make sure that line of code is even being called. If it is being called, put the "$('select.filterbox').each()" call back, then move the hide() call inside of it. If that works, then you know that it's running at least once. Change the hide() call to a (this).hide(), and see if you can see which one it's identified. Once you've narrowed down where it's failing you, it'll be a lot easier to figure out what you've done wrong.
You can do this, but it's not optimal to attach separate event handlers to a lot of elements. You can take advantage of event bubbling and just attach a single handler to their parent container. For example:
$("#filters").change(function (evt) {
// evt.target will give you actual element that changed
$("#filters select.filterbox").each(function () {
// other stuff
});
});

jQuery form validation questions?

I am new to jQuery and javascript and I am used mainly to php. I am upgrading my site so it contains a little ajax to improve usability and to keep me busy!
I am using this simple little script I threw together for the login page. All works well at the minute but I have a couple of questions I'd like to ask!
$('#loginForm .submit').click(function(event) {
$('.error').hide();
event.preventDefault();
var errors = 0;
var loginEmail = $('#loginEmail').val();
var loginPassword = $('#loginPassword').val();
if (loginEmail.length == 0) {
$('#loginEmail').after('<div class="error"></div>');
errors++;
}
if (loginPassword.length == 0) {
$('#loginPassword').after('<div class="error"></div>');
errors++;
}
if (!errors) {
$('.submit').submit();
}
});
You will notice that the first line of code within the function is;
$('.error').hide();
Now in php I would normally use;
if (isset(........)) {
Is there a simliar way to do this in javascript as when the user first activates the function there will be no html with the class .error?
Also I am trying to add a new parameter to the function as well as the event parameter, how would I do this? I have tried the following?
$('#loginForm .submit').click(function(event, var) {
$('#loginForm .submit').click(function(event var) {
$('#loginForm .submit').click(function('event', 'var') {
And all seem not to work. Then again I am going by php, jQuery/javascript is not my strong point!
Thanks
Before performing an action, you can check if the function $() selected element by using the following syntax:
if ($('.error').length)
{
// actions
}
If the .error - div exists in the DOM by default and is just hidden, you can't just check the length of $('.error'), because even if it's empty, length will return 1.
You could do something like this:
if($('.error').html().length !== 0){
//do something
}
This will check the containing string of the error-div, so if it's empty, length will return 0.
Still I would recommend setting a boolean var. If errors occur, it gets set to false and you can check the var and you do not have to query for DOM-elements for such a simple task.
To your second question, try something like this:
$('#loginForm .submit').bind("click", {variable1: var}, handleSubmit);
function handleSubmit(event){
var passedVar = event.data.variable1;
}

Bind event to a div appearing

Can I create an event so I can execute some javascript whenever an element with a specific ID becomes visible or appears on the page?
The element comes from a remote resource (so isn't in MY html code but appears on page load) and I'd like some code to run when it appears (and only if it appears, it may not appear every load).
Thanks!
You can make a function that will check every X milliseconds if such element appeared on the page (a plain Javascript solution):
(​function ()​ {
var intervalId = window.setInterval(function() {
if (null != document.getElementById('myDivId')) {
// the div appeared on the page
// ... do your stuff here:
alert('its here!');
// optionally stop checking (obviously it's there already
// unless you decide to remove it)
window.clearInterval(intervalId);
};
}, 100); // perform check every 100 milliseconds
}​)()​;
There is the possibility that the DIV is there all the time, only not visible. So your checking function should be a little different:
var el = document.getElementById('myDivId');
if (null != el && (el.offsetWidth > 0 || el.offsetHeight > 0)) {
Basically (el.offsetWidth > 0 || el.offsetHeight > 0) indicates that element is not hidden by its or its parents' CSS properties.
If a selector doesn't find a match, it just won't run, so just having code like this is fine:
$("#elementID").each(function() {
//do something
});
Just run that statement in whatever code loads the ID, or alternatively rig it up in the ajax handler if that's how it's getting loaded like this:
$.ajaxSetup({
complete: function() {
$("#elementID").each(function() {
//do something
});
}
});
You could use live() method:
$('div_id_or_class').live('click', function(){
// ................
});

Categories

Resources