How to hide div after page loads in plain Javascript? - javascript

I've viewed a couple of the posts in here regarding this topic but not quite working for my situation. I'm using Tampermonkey userscript manager. I want to hide a bunch of div's after the page is fully loaded. I've tested the code below on the console of the page and it works.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This alert also works with the Tampermonkey userscript manager.
window.addEventListener("load", function(){
// code goes below
alert("hello world");
});
However, the following code is not working. Neither the div or the alert is working in this situation.
window.addEventListener("load", function(){
// ....
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
alert("it's working");
});
By the way, I'm a newbie to Javascript so any help is much appreciated.

You currently only hide the first ([0]) div. You need to iterate over all elements to hide them.
I'd suggest using document.querySelectorAll because it's easily iterable:
window.addEventListener("load", function(){
document.querySelectorAll('promotions-personalized-offers-ui-single-offer')
.forEach(e => (e.style.display = 'none'));
});
If you must stick to getElementsByClassName, a spread should do the trick:
window.addEventListener("load", function(){
[...document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')]
.forEach(e => (e.style.display = 'none'));
});

Try this:
var x = 3 //number of div elements to remove
window.onload = function() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
The divs would need to look like this:
<div id="div1">Content</div>
<div id="div2">Content</div>
<div id="div3">Content</div>
Alternatively, if you're putting the JavaScript code inside a function that's called after the page loads fully, you can just use this:
var x = 3 //number of div elements to remove
function removeDivs() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
Then call the function by using removeDivs().

Tampermonkey by default runs when the DOMContentLoaded event is dispatched. https://www.tampermonkey.net/documentation.php#_run_at Based on what you have posted it does not look like you need the event listener at all. Your script would only need one line.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';

Related

Storing variable via .text() isn't uptodate

I have <span> tags in a div that is removed when user clicks on them. Works fine.
I want to store the .text() inside that div in a variable. The problem is that the updated text doesn't get stored.
Click on a word to remove it in this jsFiddle.
As you can see, the content variable returns the old text, not the new revised one.
How can I store a variable with the updated text?
jQuery:
jQuery(document).ready(function() {
jQuery(document).on("mousedown", ".hello span", function() {
// don't add full stop at the end of sentence if it already ends with
var endChars = [".", "?", "!"];
jQuery(this).fadeOut(function(){
var parentObj = jQuery(this).parent();
jQuery(this).remove();
var text = parentObj.find("span").first().html();
parentObj.find("span").first().html(ta_capitalizeFirstLetter(text));
text = parentObj.find("span").last().html();
if ( endChars.indexOf(text.slice(-1)) == -1 )
{
parentObj.find("span").last().html(text+".");
}
});
var content = jQuery(this).parent().parent().find('.hello').text();
alert(content);
});
});
The code to get the new text should be moved inside the fadeOut callback. Once the animation is completed and element is removed, then the innerText of the parent element will be updated. At this time, the updated content should be read from the DOM.
Demo
// Cache the element
var $el = jQuery(this).parent().parent().find('.hello');
jQuery(this).fadeOut(function () {
jQuery(this).remove();
// Irrelevant code removed from here
...
var content = $el.text();
alert(content);
});
Here's another simple demo with minimal code that'll help to understand the code better.
Demo
I tried to debug your jsfiddle in chrome, and it looks like the priority of your code is like this:
declare on this event - jQuery(this).fadeOut(function(){
get the the current data of the div var content = jQuery(this).parent().parent().find('.hello').text();.
alert your data without changes.
calling the funcntion of fadeout
I think all you have to do is to call your alert and 2 from your anonymous function of fadeout
Just put your alert inside the callback:
jQuery(this).fadeOut(function(){
var parentObj = jQuery(this).parent();
jQuery(this).remove();
var text = parentObj.find("span").first().html();
parentObj.find("span").first().html(ta_capitalizeFirstLetter(text));
text = parentObj.find("span").last().html();
if ( endChars.indexOf(text.slice(-1)) == -1 ) {
parentObj.find("span").last().html(text+".");
var content = parentObj.parent().find('.hello').text();
alert(content);
}
});

Dynamically display html elements via loop

I am working with javascript and jquery. I want to be able to display a buttom, some text, and/or really any html elements or components as many times as the loop allows. I am able to loop through and print alert statements
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++)
{ alert("count: " + i); }
}
Simple enough. This would give me 5 alert statements, but instead of using alert statements, I want to be able to display a button or some text or any other html elements. So I would get five buttons displayed on an html page. Is this possible? I'm actually using a .foreach function but for ease of use, a regular for loop would suffice for now. I want to be able to do this on button click (i.e., the function that has the loop starts running once I click a button) also. I'm just not sure really how to accomplish this. Any help would be greatly appreciated. Thanks in advance.
With vanilla Javascript (without using jQuery):
You can use document.createElement to create any type of element you want on the page. Here's the above loop creating <INPUT TYPE='BUTTON'> elements in a <div> with an id of test:
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++) {
var v = document.createElement('input');
v.type="button";
v.value="Button " +i;
document.getElementById('test').appendChild(v);
}
}
(In general, using document.write has been considered a bad practice for a while now.)
With jQuery, you can do:
for (i=0;i<5;i++) {
var btn = $("<button/>");
btn.text('Button '+i);
$('#test').append(btn);
}
You can use innerHTML field to add any html content into container on you page.
<script>
function LoopTest()
{
var i=0;
var stop=5;
for (i=0;i<5;i++)
{
document.getElementById("container").innerHTML += "<button>button</button>"
}
}
</script>
...
<div id="container"></div>
Refer: document.write(), Javascript events
<html>
<head>
<script>
function LoopTest() {
var i=0;
var stop = 5;
for (i=0;i<5;i++)
{
document.write('<p>' + i + '</p>'); // This writes the number in a paragraph
}
}
</script>
</head>
<body>
<!--
Here onclick event is used to recognize the click event,
which is fired when the user clicks the button,
this calls the LoopTest() function which generates 5 paragraphs with numbers
-->
<button onclick="LoopTest()">Click to generate content!</button>
</body>
</html>
This is a solution : http://jsfiddle.net/leojavier/gbuLykdj/
<div class="container">
<button class="trigger">Trigger</button>
</div>
JS
$('.trigger').on('click', function(){
LoopTest();
});
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++){
$('body').append('<button class="trigger">Trigger No. ' + i + '</button>')
}
}

jQuery click not working for dynamicly created elements

I looked at the other solutions on SO for this problem and none of them seem to help my case. To give you some background, yesterday I was trying to select all DIVs by a class and store their IDs. See this Now that I have the IDs I want to create some new elements and incorporate the IDs and be able to click on these new elements. I went to JSFiddle to show you a demo but the crazy part is over there, my code works, yet in my app (Chrome extension) it doesn't. What's even crazier is that I'm already implementing jQuery click events in other parts of it without a problem so I'm really confused why it's not working in this particular case. Here's the JSFiddle that works but in my app it doesn't do anything on click. Thanks for any help! I'm sorry for posting so many (silly) questions.
HTML:
<div class="HA" id="k2348382383838382133"></div>
<div class="HA" id="k2344444444444444444"></div>
<div class="HA" id="k234543544545454454"></div>
<div class="HA" id="k2346787878778787878"></div>
JS:
var HAContainer = document.querySelectorAll('.HA');
var HALength = document.querySelectorAll('.HA').length;
var id = [];
var j = 0;
$('.HA').each(function(){
id[j++] = $(this).attr('id');
});
for (var i=0; i<HALength; i++) {
var HABtn, HABtnImg, HAImgContainer;
HABtnImg = document.createElement("img");
HABtnImg.src = ("http://www.freesmileys.org/smileys/smiley-laughing002.gif");
HABtnImg.className = "ha-icon";
HAImgContainer = document.createElement("div");
HAImgContainer.setAttribute("id", 'HA-'+id[i] + '-container');
HAImgContainer.appendChild(HABtnImg);
HABtn = document.createElement("div");
HABtn.className = 'ha-button';
HABtn.setAttribute("id", 'HA-container');
HABtn.appendChild(HAImgContainer);
HAContainer[i].appendChild(HABtn);
HAClick(id[i]);
}
function HAClick(id) {
$('#HA-'+id+'-container').click(function() {
alert("clicked on ID " + id);
});
}
You have to delegate your event in order to make it work with dinamically added elements:
$('body').on("click", '#HA-'+id+'-container', function() {
alert("clicked on ID " + id);
});
I've noticed something and will edit with a better approach:
Change:
HABtn.setAttribute("id", 'HA-container');
To:
HABtn.setAttribute("id", 'HA-'+id[i] + '-inner-container');
HABtn.setAttribute("class", 'HA-container');
And instead of:
function HAClick(id) {
$('#HA-'+id+'-container').click(function() {
alert("clicked on ID " + id);
});
}
simply attach once the event with delegation:
$('body').on("click", '.HA-container', function() {
alert("clicked on ID " + $(this).attr('id'));
});
jsFiddle implicitly selects the javascript you use to be placed inside of an onload event handler.
As a result your code is wrapped with the onload event handler and basically looks likes this
window.onload = function(){
//your code here
};
The reason it works in jsFiddle is because the script is executing once the DOM is loaded and thus can interact with the elements as they are in the DOM. It is possible that your chrome extension is not acting after the elements have been loaded.
It would be prudent to wrap your javascript in the document.ready shortcut
$(function(){
//your code here
});
Given that, there are still some issues which exist in your code. It is not clear why you need to have that nested div structure, perhaps as a result of css styling, but one issue is the duplication of ids. They could probably just be class names (I am referencing "HA-container").
jQuery offers a very easy way to create elements in the constructor that you can take advantage of here. It will allow your code to be more streamlined and readable.
Further, you can store the id you use inside of the container element's jquery object reference for data using .data('id',value). This will all you to also assign the click event handler immediately inside of using another function to assign it.
jsFiddle Demo
$('.HA').each(function(){
var btn = $('<div class="ha-button HA-container">');
var cont = $('<div id="'+this.id+'-container">').data('id',this.id);
cont.click(function(){ alert("clicked on ID " + $(this).data('id')); });
var img = $('<img src="http://www.freesmileys.org/smileys/smiley-laughing002.gif" class="ha-icon" />');
$(this).append(btn.append(cont.append(img)));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="HA" id="k2348382383838382133"></div>
<div class="HA" id="k2344444444444444444"></div>
<div class="HA" id="k234543544545454454"></div>
<div class="HA" id="k2346787878778787878"></div>
I'd re-write it a bit to take advantage of jQuery:
for (var i=0; i<HALength; i++) {
var HABtnImg = $('<img/>')
.attr('src', 'http://www.freesmileys.org/smileys/smiley-laughing002.gif')
.addClass('ha-icon');
var HAImgContainer = $('<div/>')
.attr('id', 'HA-'+id[i] + '-container')
.append(HABtnImg);
var HABtn = $('<div/>')
.addClass('ha-button')
.append(HAImgContainer);
//don't use duplicate ID's here
$(HAContainer[i]).append(HABtn);
}
And later attach the event like so:
$(document).on('click', '.ha-button', function(e){
//your click code here
var id = $(this).find('div').attr('id');
alert("clicked on ID " + id);
});

Create my own Radio-like-button with a DIV?

I'm trying to make a site where users can create there own social networking buttons. (I know its been done but its mostly for practice). A part of the site will allow users to choose the shape of the buttons. Here is the HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
What I would like to do is add an event listener when the div is clicked. After it's clicked the class attribute would be changed to "selected." When another one would be click then the first clicked one would be cleared and the next one would be selected. Just like with radio buttons.
I am familiar with JavaScript and my idea was this:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
A more simple version of scdavis41's answer:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
I also put a selector that includes the control's main div id in case you want to put this control more then once in your page.
** EDIT **
If you absolutly want to use javascript and DOM try this:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
This is verbose, but you could use:
$(document).ready(function(){
$('#square').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#circle').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
$('#rounded').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
This is jQuery, which means you have to load the jQuery library, but putting this above your script tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
If you are looking for a pure JavaScript solution, you could try this:
if(option == 'add'){
element.className = element.className + ' selected';
element.onclick = function() {select(this.id, 'remove')};
element.innerHTML = '✓';
}
else if(option == 'remove'){
element.className = element.className.replace(/\bselected\b/,'');
element.onclick = function() {select(this.id, 'add')};
element.innerHTML = '';
}
JSFiddle: http://jsfiddle.net/hKePD/
**EDIT**
Or if you were looking for a checkbox to be always checked, you could try this: http://jsfiddle.net/hKePD/1/
Building on scadvis41's answer, this is much shorter:
$(document).ready(function(){
$('.shapeSelect').click(function(){
$('.shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});

JavaScript - Toggle function

Im trying to hide/show a JS function I have defined in a chrome extension.
What I have so far:
The span classes I am trying to hide are label:
dspan.className = "cExtension";
//Create toggle button:
function createToggleButton(){
var toggleButton = document.createElement("button");
toggleButton.innerHTML = "Toggle Overlay";
toggleButton.id = "Toggle"
var header = document.getElementById("header");
header.appendChild(toggleButton);
toggleExtension();
}
// find all spans and toggle display:
function toggleExtension(){
var spans = document.getElementsByTagName('span');
var toggle = function() {
for (var i = 0, l = spans.length; i < l; i++) {
if (spans[i].getAttribute('class') == 'cExtension')
if (spans[i].style.display == 'none') spans[i].style.display = '';
else spans[i].style.display = 'none';
}
}
document.getElementById('Toggle').onclick = toggle;
}
The button shows on the header, however it is unclickable. If I change document.getElementById('Toggle').onclick = toggle; to document.getElementById('Toggle').onclick = alert{"Hello"); the alert is triggered on page load on not onclick. I am trying to get this done in pure JS. Where am I going wrong?
First of all, document.getElementById("Toggle").onclick = alert("Hello"); will set the onclick event to whatever the alert function returns, not the alert function itself. So the alert function happens at page load so it can figure out what to return. So you could do this: document.getElementById("Toggle").onclick = function(){alert("Hello");}; and that might work.
Edit: Scratch everything that was here: I missed that toggle variable set to a function in toggleExtension.
I haven't tested all this so I can't guarantee that it'll all work in your specific case.
if visible is set remove it, otherwise add it
div.classList.toggle("visible");
add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );
Make sure browser support: http://caniuse.com/#feat=classlist
Why not use jQuery?
It will do all hard job for you.
http://api.jquery.com/toggle/
Cheers!

Categories