Why doesn't the removeChild remove the element? - javascript

I have written this scrip to take out ads on a website. Was working on it the whole day.
This is the JS code:
var timer = setInterval(deletor, 1);
function deletor() {
timer;
var slider = document.querySelector("#slider-con");
var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
var bannerMiddle = document.querySelector("#MainContent > iframe");
var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");
var bannerRandom2 = document.querySelector("#MainContent > div:nth-child(6)");
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
if (bannerTop == undefined) {
return false;
} else {
bannerTop.parentNode.removeChild(bannerTop);
};
if (bannerMiddle == undefined) {
return false;
} else {
bannerMiddle.parentNode.removeChild(bannerMiddle);
};
if (bannerRandom == undefined) {
return false;
} else {
bannerRandom.parentNode.removeChild(bannerRandom);
};
if (bannerRandom2 == undefined) {
return false;
} else {
bannerRandom2.parentNode.removeChild(bannerRandom2);
};
};
Now, as you can see, it gets the values first and then goes through if statements. Idea behind this is: On first try, it deletes the elements and on the second one, it stops the function.
But when I inserted this last element, it won't delete it. The ID is correct, everything is correct but it won't delete the element, so I keep getting the same alert over and over.
Also, I found out that, I get this banner ad on two places. When I have "var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");" this, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this, and when I have both, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this. And it's not deleted.
Console shows no errors.

Your various statements in the form:
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
mean this: "If slider wasn't found in the DOM, exit the function. Otherwise, remove the slider and continue the function."
So that means your function will terminate the first time one of the elements you're looking for doesn't exist. Since it terminates then, none of the other elements after it is checked. That seems unlikely to be what you want to do.
You probably just wanted:
if (slider) {
slider.parentNode.removeChild(slider);
}
...and so on.
Note that you don't put ; at the end of a block attached to a flow-control statement like if or else, which is why I've removed it above. (Doing so is harmless, because JavaScript ignores them; but it's pointless.)

Related

How to synchronise ExtJS "checkboxes" (buttons) with Javascript/JQuery?

I am currently trying to synchronize two checkboxes on a page.
I need the checkboxes to be synchronized - to this end, I'm using a Tampermonkey userscript to pick up when one of them is clicked. However, I'm at a loss as to how to do it.
I believe they are not actually checkboxes, but ExtJS buttons that resemble checkboxes. I can't check whether they're checked with JQuery because of this: the checked value is appended to a class once the JS behind the button has run.
I have tried preventDefault and stopPropagation, but either I'm using it wrong or not understanding its' usage.
I'm not quite clever enough to just call the JS behind the box instead of an onclick event. Otherwise, that would solve my issue.
This is my code:
//Variables - "inputEl" is the actual button.
var srcFFR = "checkbox-1097";
var destFFR = "checkbox-1134";
var srcFFRb = "checkbox-1097-inputEl";
var destFFRb = "checkbox-1134-inputEl";
//This checks if they're synchronised on page load and syncs them with no user intervention.
var srcChk = document.getElementById(srcFFR).classList.contains('x-form-cb-checked');
var destChk = document.getElementById(destFFR).classList.contains('x-form-cb-checked');
if (srcChk == true || destChk == false) {
document.getElementById(destFFRb).click();
} else if (destChk == true || srcChk == false) {
document.getElementById(srcFFRb).click();
}
//This is where it listens for the click and attempts to synchronize the buttons.
$(document.getElementById(srcFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(destFFRb).click();
}
});
$(document.getElementById(destFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(srcFFRb).click();
}
});
I'm at a bit of a loss...any help would be greatly appreciated.
Figured it out - I was comparing class lists without singling out what I wanted to actually match.
My solution:
$(document.getElementById(srcFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(destFFRb).click();;
}});
$(document.getElementById(destFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(srcFFRb).click();;
}});

else condition is always executed even if the if statement is true

I am trying forever to fix this code: i have a list and i am searching through the list to find students. Once i don't find a student, an error message should appear. At the moment i have a function who searches the student based on text match. I have an if statement inside the function. When the match is found show student and when not, hide all the students. I created a variable 'found' set to 'true' when the student is found. if this is false the message should be appended.
The problem is that both conditions are being executed it seems so if i put found as being false inside the second condition the error message will display every time.
At the moment i have another if which checks if found was false. the problem is it doesn't recognise that it is false...so confusing. Please see screenshot with the console where you can see that although the student is found, the second condition is executed each time... screenshot with the console - second condition is always executed
First condition doesn't execute unless it's true.
Please help as I am trying to investigate this forever and I asked lots of questions here around this issue but with no big results.
Thanks so much,
Alina
var ul = document.getElementsByClassName("student-list");
var li = document.getElementsByTagName("li");
//add search bar
$( ".page-header" ).append('<div class="student-search"></div>');
$( ".student-search" ).append('<input id="input-search" placeholder="Search for students..."/><button id="search">Search</button>');
// append to the .page the container div for the error message
$('.page').append('<div class="error"></div>');
// append to the error div a p with the error message if student is not found
var found = true;
//myFunction
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
for (var i = 0; i < li.length; i+=1) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
li[i].style.display = "";
console.log('yey found it');
found = true;
} else {
li[i].style.display = "none";
console.log('condtion 2');
}
}
if (found===false) {
$('.error').append('<p>"student not found!"</p>');
}
$('.pagination').hide();
}
//myFunction end
$('#search').on('click', function(){
myFunction();
});
// when the input is empty return to page 1, empty the error div, show pagination,
$('#input-search').on('keyup', function() {
if($(this).val() === '') {
go_to_page(0);
$('.pagination').show();
}
});
I think the function is called more than once judging that 'condition 2' got logged 50 times , and the condition isn't satisfied every time,
To make sure that it doesn't reach the else statement even if the code entered the if statement edit the function to be like this:
function myFunction() {
var input = document.getElementById("input-search");
var filter = input.value.toUpperCase();
found = false
for (var i = 0; i < li.length; i+=1) {
var h = li[i].getElementsByTagName("h3")[0];
if (h.innerHTML.toUpperCase().indexOf(filter) != -1) {
li[i].style.display = "";
console.log('yey found it');
found = true;
} else {
li[i].style.display = "none";
console.log('condtion 2');
}
}
if (found===false) {
$('.error').append('<p>"student not found!"</p>');
}
$('.pagination').hide();
console.log('--------------------------------------');
}
That way you see how many times the function was being called

Jquery keydown only works once

EDIT: I solved it by changing = to ==, but that didnt fully solve it but then I added a change to $currentSlide and now it works! Yay!
$(document).keydown(function(e) {
if(e.keyCode == 39)
{
if($currentSlide == $slide1){
slideShow(slide2);
$currentSlide = $slide2;
}
else if($currentSlide == $slide2){
slideShow(slide3);
$currentSlide = $slide3;
}
else if($currentSlide == $slide3){
slideShow(slide1);
$currentSlide = $slide1;
}
}
})
I have searched for an answer but haven't found anything that suits my question. I am a noob on javascript so bear with me.
I have a function that works as a slideshow. (I use $ in front of my jquery variables, I have a lot of javascript variables too so I just use it to separate them.)
var $currentSlide = "#slide1";
var $slide1 = "#slide1";
var $slide2 = "#slide2";
var $slide3 = "#slide3";
function slideShow($slide) {
if ($slide != $currentSlide){
$($currentSlide).fadeOut(500);
$($slide).delay(500).fadeIn(500);
$currentSlide = $slide;
}
};
To call this function, I use a simple link with parameter depending on which slide is active.
onclick="slideShow(slide2)"
And then I want to change slide with keypress (to right). This is my code for the keypress:
$(document).keydown(function(e) {
if(e.keyCode == 39) {
if ($currentSlide = $slide1){
slideShow(slide2);
} else if($currentSlide = $slide2) {
slideShow(slide3);
} else if($currentSlide = $slide3) {
slideShow(slide1);
}
}
})
It works perfectly when using the links but when I press key it behaves very weird. First click works like a charm, but then it doesnt work any more. If I click to get the third slide, another click will put next slide on top of slide3 but slide3 never goes away.
I realise there is some huge mistake by me here but I'm too much of a beginner to fix it. Any ideas?
your if-else conditions will always be true, because you used '=' instead of '=='. since your first if condition will be true it always shows slide2 and it looks to you that it only worked once
$(document).keydown(function(e) {
if(e.keyCode == 39) {
if ($currentSlide == $slide1){
slideShow(slide2);
} else if($currentSlide == $slide2) {
slideShow(slide3);
} else if($currentSlide == $slide3) {
slideShow(slide1);
}
}
})
The second problem maybe caused by the clock on the slideshow, if you are using one. When you click the next/previous button you need to reset the clock of your slideshow.
There are two issues
You do an assignment in your if conditions, so they always are true. Instead use the comparator ===;
In the onclick attribute you specify an undefined variable, since the $ is missing from it
Beside correcting this, I would suggest to use a class for your slide elements, not individual IDs. So use class="slide" instead of id="slide1" in your HTML, and apply it to all slides -- they can share the same class.
Then store the sequence number of the current slide, counting from 0.
I would also remove all the onclick attributes on the slide elements and deal with click handlers from code, which can be done quite concisely with $('.slide').click( ... ):
var currentSlideNo = 0; // zero-indexed
function slideShow(slideNo) {
if(slideNo != currentSlideNo){
$('.slide').get(currentSlideNo).fadeOut(500);
currentSlideNo = slideNo;
$('.slide').get(currentSlideNo).delay(500).fadeIn(500);
}
};
$('.slide').click(function () {
slideShow((currentSlideNo + 1) % $('.slide').length);
});
$(document).keydown(function(e) {
if (e.keyCode == 39) {
slideShow((currentSlideNo + 1) % $('.slide').length);
}
});

Unhide div using javascript object oriented

So i am having trouble unhiding a div, once it has been hidden.
The code:
First object
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId($temp_region_id);
});
Seconds object:
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide(); }
else { $('.showheadline').show(); }
}
Really what i want to do, is once the region is changed from the original, the div should be hidden - this works!
However, once the person goes back on the same region, the div is still hidden.
The filter_region echos from 1-8 depending on the region. I realise that i have set the region to 1, this is to test. However, even if the if-statement is set to 1, it still shows the divs when loaded, even if the region is 2-8. Hope this make any sense at all! Please feel free to ask if there are any questions regarding my explanation.
Best Regards,
Patrick
Try this, without the $(..) around the var
$('#filter_region').on('change', function(e) {
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if (temp_region_id != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}
A text input's value attribute will always return a string. You need to parseInt the value to get an integer
var temp_region_id = parseInt($('#filter_region').val(),10);
and remove the $ from variable name filterRegionId($temp_region_id); and if ($(temp_region_id) != 1) {
$('#filter_region').on('change', function(e) {
var temp_region_id = parseInt($('#filter_region').val(),10);
///parse it to integer
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id){
if (temp_region_id!= 1)
$('.showheadline').hide();
else
$('.showheadline').show();
}
The best solution is to rewrite you code a little.
Please add the filterRegion function on top and change the parametter name as follows
var temp_region_id = $('#filter_region').val();
filterRegionId(temp_region_id);
$('#filter_region').on('change', function(e) {
temp_region_id= $('#filter_region').val();
filterRegionId(temp_region_id);
});
function filterRegionId(temp_region_id)
{
if ($(temp_region_id) != 1) {
$('.showheadline').hide();
}
else {
$('.showheadline').show();
}
}

Javascript function works not as intended when I move mouse too quickly. Ideas on how to improve?

I have a drag-and-droppable control on my page. It has a client-side event 'OnClientDragging' which I am using to provide highlighting to my page. The idea is that there are various zones on the page and, as the user drags the control over parts of the page, the page gets highlighted accordingly.
The problem is that I see the highlighting flicker slightly when moving fast. I do not see any exceptions being thrown, but if I move the mouse rapidly while staying inside of one 'zone' I still see the highlighting being removed and re-added. I can only assume this is because the method is not completing in time -- and fires again due to being dragged more.. which causes unintended issues?
function RemoveHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.removeCssClass("zoneDropOk");
}
}
function AddHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.addCssClass("zoneDropOk");
}
}
var previousZone = null;
//Evaluates whether the currently moused-over item is a RadDockZone.
function TryGetZoneFromTarget(target) {
while (target != null && target.id) {
if (target.id.indexOf("RadDockZone") != -1) {
return $find(target.id);
}
target = target.parentNode;
}
return null;
}
//Adds highlighting to the dockZones when the user is dragging objects to the screen.
//Clear the old dockZone as the user moves out of it, and color new ones as they move into it.
function OnClientDragging(sender, eventArgs) {
var target = eventArgs.get_htmlElement();
var zone = TryGetZoneFromTarget(target);
if (zone) {
var currentZone = zone;
dockZoneDroppedOnID = zone.get_id();
if (previousZone == null) {
previousZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
else if (previousZone != currentZone) {
$.queue(RemoveHighlighting(previousZone));
previousZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
}
else {
dockZoneDroppedOnID = "";
if (previousZone != null && $.queue.length == 0) {
RemoveHighlighting(previousZone);
previousZone = null;
}
}
}
Should I be trying to make this script more efficient, or maybe setting a variable outside the local scope to indicate that the previous event is still running and cancel the current event?
EDIT: I've edited in a queue solution which worked well! I'm not sure if it's a perfect solution, but it solved my issue.
I think setting variables outside this scope will be a more effective approach, in particular, you can either make use of or emulate the way jQuery's fx queue works.

Categories