Javascript: Clicking an injected button doesn't work - javascript

when I inject some code the onclick doesn't work
here is the code I use.
document.getElementById('headbar').onclick = function() {
var list_div_preleva = document.getElementsByClassName('preleva_dati').length;
var list = document.getElementsByClassName('box_commenti');
for(var i = list_div_preleva; i < list.length; i++) {
var parentDiv = list[i].parentNode.id;
var id_post = document.getElementById(parentDiv);
var creaelementodiv = document.createElement("button");
creaelementodiv.className = "preleva_dati";
creaelementodiv.setAttribute("id", "blocco_dati");
creaelementodiv.innerHTML = "<li>preleva il post</li>";
id_post.appendChild(creaelementodiv);
}
};
<div id="headbar">div</div>
when the code is inside, onclick doesn't work
<!-- begin snippet: js hide: false console: true babel: false -->
document.getElementById('blocco_dati').onclick = function() {
alert(11);
};
can the problem be solved?

document.getElementById('headbar').onclick = function() {
var id_post = document.getElementById("headbar2");
var creaelementodiv = document.createElement("button");
creaelementodiv.className = "preleva_dati";
creaelementodiv.setAttribute("id", "blocco_dati");
creaelementodiv.innerHTML = "preleva il post";
creaelementodiv.setAttribute("onclick", "doSomething();");
id_post.appendChild(creaelementodiv);
};
function doSomething() {
alert(11);
};
<div id="headbar">div</div>
<div id="headbar2"></div>
You can set one more attribute while injecting element
for ex:
creaelementodiv.setAttribute("onclick", "doSomething();");
and then you can call that function like
function doSomething() {
alert(11);
};

Related

Google Apps Script function is executing twice if I remove ui.alert()

I have a function to extract all the image captions in a Google docs which is being called using a button in my Plug-in, the problem is when I comment the ui.alert() part the function is executing twice. The code is:
function refFig() {
var body = DocumentApp.getActiveDocument().getBody();
// var ui = DocumentApp.getUi();
// ui.alert('Inside the function');
var images = body.getImages();
var images_caption = [];
var j = 1;
for (i = 0; i < images.length; i++) {
var image = images[i];
var linkString = image.getLinkUrl();
if (linkString != null) {
var caption = linkString.slice(15, linkString.length);
var refUrl = '#D2L_fig_ref_' + caption;
images_caption[j++] = refUrl;
}
}
return images_caption;
}
The jquery used to call the function is:
$(document).ready(function() {
$('#refFig').click(call_refFig);
});
function call_refFig() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(after_refFig)
.withFailureHandler(function(msg, element) {
showError(msg, $('#button-bar'));
element.disabled = false;
}).refFig();
}
The HTML of the button is:
<div id="div_refFig" style="padding-left:0px">
<a id="refFig" href="#!" class="collection-item grey-text text-darken-3">
<i class="material-icons d2ltheme left">find_replace</i>
Refer
</a>
</div>

Simple shortening of my code

I am looking for a way to simplify this code using for loops. Any help is appreciated.
I am setting up a system of opening modal frames full of images when somebody clicks on a link with a date on it (e.g. a photo archive). I have a lot of different dates and each time I make a new one I have to insert it a million times into the code as shown below. Maybe I could make an array of some sort that holds the dates and loop through the array and generate the code below. There is probably a simple fix to this, but I am new to web development. Thanks!!!!
// Get the modal gallery
var gallery161207 = document.getElementById('gallery161207');
var gallery161130 = document.getElementById('gallery161130');
...
var gallery150916 = document.getElementById('gallery150916');
// Get the close button
var closeButton161207 = document.getElementById('closeModal161207');
var closeButton161130 = document.getElementById('closeModal161130');
...
var closeButton150916 = document.getElementById('closeModal150916');
// Get the buttons
var btn161207 = document.getElementById('161207');
var btn161130 = document.getElementById('161130');
...
var btn150916 = document.getElementById('150916');
// When the user clicks on the button, open the modal gallery
function openGallery(source) {
// Open the modal gallery depending on what was clicked
if (source == '161207')
gallery161207.style.display = "block";
if (source == '161130')
gallery161130.style.display = "block";
...
if (source == '150916')
gallery150916.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
closeButton161207.onclick = function() {
gallery161207.style.display = "none";
}
closeButton161130.onclick = function() {
gallery161130.style.display = "none";
}
...
closeButton150916.onclick = function() {
gallery150916.style.display = "none";
}
btn161207.onclick = function() { openGallery('161207'); }
btn161130.onclick = function() { openGallery('161130'); }
...
btn150916.onclick = function() { openGallery('150916'); }
window.onclick = function(event) {
if (event.target == gallery161207) {
closeButton161207.onclick();
}
if (event.target == gallery161130) {
closeButton161130.onclick();
}
...
if (event.target == gallery150916) {
closeButton150916.onclick();
}
}
You could do this fairly easily using jQuery, but I assume, since you're new to web development, you'll want to start out from scratch.
First, let's deal with setting up the buttons to show the galleries. I'd say you give each button a class="gallery-button" attribute and an id="<id of gallery>". The galleries also should have IDs id="gallery-<id of gallery>". Then:
var buttons = document.getElementsByClassName("gallery-button");
for(var i =0; i < buttons.length; i++){
var elem = buttons[i];
elem.onclick = function() {
document.getElementById('gallery' + elem.id).style.display="block";
};
}
}
We can do a similar thing for the close buttons (assuming they have IDs of id="close-<id of gallery>" and their class="close-button":
var closeButtons = document.getElementsByClassName("close-button");
for(var i =0; i < buttons.length; i++){
var elem = closeButtons[i];
elem.onclick = function() {
document.getElementById('gallery-' + elem.id.replace("close-", "")).style.display="none";
};
}
}
And then:
window.onclick = function(event) {
var id = event.target.id;
if (id.startsWith("gallery-") {
var closeButton = document.getElementById("close-" + id.replace("gallery-", ""));
closeButton.onclick();
}
}
You can try making an object saving all the dom references and using those. This answer makes use of jQuery for its document ready function.
var sourceList = [];
var sources = {};
var wrappers = document.getElementsByClassName('gallery-wrapper');
for(var i = 0; i < wrappers.length; i++){
sourceList.push(wrappers[i].id);
}
$( document ).ready(function() {
for(var i = 0; i < sourceList.length; i++){
var source = {};
source.gallery = document.getElementById("gallery"+sourceList[i]);
source.button = document.getElementById("button"+sourceList[i]);
source.closeButton = document.getElementById('closeButton'+sourceList[i]);
source.button.onclick = function() {
if(source.gallery)source.gallery.style.display = "block";
}
source.closeButton.onclick = function() {
if(source.gallery)source.gallery.style.display = "none";
}
sources[sourceList[i]] = source;
}
window.onclick = function(event) {
for (var source in sources)
if (event.target == sources[source].gallery)
sources[source].closeButton.onclick();
}
});

(Javascript) SlideShow Not Working

Hello fellow stackoverflow members,
I've been trying to make a Slideshow. I've referenced from many other sites including this one but the pictures aren't showing up in the container element nor are the "prev" and "next" buttons functioning properly. I'd appreciate it if I got help! :)
my code:
var photos = newArray ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
var i = 0;
var k = photos.length-1;
function next.onclick() {
var img= document.getElementById("image-container");
img.src = photos[i];
if (i < k ) {
i++;
}else {
i = 0; }
}
function prev.onclick() {
var img= document.getElementById("image-container");
img.src=photos[i];
if)i > 0) {i--;}
else {i = k; }
}
getImageArray = function(containerId) {
var containerElement = document.getElementById(container);
if (containerElement) {
var imageArray = containerElement.getElementById("container");
return photos[i];
} else {
return null;
}
}
this is what my slideshow looks like (it's broken)
http://prntscr.com/5dcfzq
The share button isn't important, I can make that work at least.
The main problem is that the pictures aren't showing and the back and foward buttons are messed up :'(
p.s ( I'm not sure if part of the reason is how I'm linking to the "next" or "back" functions with the div tag, because i'm this is how i'm doing it :
<div id = "back" onclick = "prev()"></div>
OK ... to summarize ...
1. var photos = newArray ();
There needs to be a space between new and Array, so ...
var photos = new Array();
2. function prev.onclick() { needs to be just function prev() {
3. Same with next.onclick() based on usage in HTML.
4. In prev() ... if)i > 0) {i--;} should be ...
if (i > 0) { i--; }
5. WRONG: Also in prev()' ... else should bei = k-1;`
6. DO NOT NEED Not sure why you have the getImageArray function at all.
7. This assumes there is an '' tag in the HTML.
UPDATE:
Here's the code that works ... this all goes in the body:
These are my assumptions in the body ...
<img id="image-container" />
<div id="back" onclick="prev()">Previous</div>
<div id="next" onclick="mext()">Next</div>
The script code MUST be at the end of the body ...
<script>
var photos = new Array ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
// Here, I set the img variable so that it can be re-used.
// I also loaded the first image ...
var i = 0;
var k = photos.length-1;
var img = document.getElementById("image-container");
img.src = photos[i];
function next() {
img.src = photos[i];
if (i<k) {
i++;
} else {
i = 0;
}
}
function prev() {
img.src=photos[i];
if (i>0) {
i--;
} else {
i = k;
}
}
</script>

js sort by id on button

http://jsfiddle.net/fkling/nXkDp/
Hi, im trying to hookup this script onto button, but it's not working. i have no idea why.
var sortID = function()
{
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);}
};
Create a button and onload, assign it's onclick handler to your sortID() function:
jsFiddle Demo
HTML:
<input type="button" id="mybutton" value="Sort" />
Javascript:
var sortID = function () {
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function (a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for (var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
};
window.onload = function(){
document.getElementById("mybutton").onclick = sortID;
}
Try this :
HTML :
<div id="list">
<div id="categorie5.1-4">4</div>
<div id="categorie5.1-3">3</div>
<div id="categorie5.1-5">5</div>
<div id="categorie5.1-1">1</div>
<div id="categorie5.1-2">2</div>
</div>
<input type="button" onclick="keyMe()" value="hook">
Javascript :
function keyMe(){
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
}
I hope it will help you
here is the link : jsfiddle.net/dp6Vr/
You can assign an event handler to a button as follows:
document.getElementById('sortButtonIdHere').addEventListener('click', function() {
// your code here
}, false);
Demo: http://jsfiddle.net/nXkDp/31/
If you're concerned about supporting IE8 and older, you could use:
document.getElementById('sortButtonIdHere').onclick = function() {
// your code here
};
Or you could add a test for whether .addEventListener() is defined and if not use attachEvent() as explained at MDN.

Button handling and layer visibility in Greasemonkey

I have a Greasemonkey script that I've been building for a game. The idea is to have info about the game in a div that will pop up when a button (which is added by my script) on the page is clicked.
I'm using z-index because when I just display the div over the top of the game screen, some of the images show through. So, basically what I need to do is change the z-index of my div based on the value of a variable and/or button click. However, I cannot get my div to come to the front when I click my button.
Here's what I have so far:
// ==UserScript==
// #name Test Script
// #namespace http://therealmsbeyond.com/
// #description Test
// #include an_include.js
// #include another_include.js
// #require json.js
// ==/UserScript==
var VERSION = 1;
var WEBSITEURL = 'http://therealmsbeyond.com/';
var SCRIPTNAME = 'Test';
var SENDINFODELAY = 600000;
var UPDATEDELAY = 604800000;
var ZINDEX_UNDER = -100;
var ZINDEX_OVER = 111111;
var Options = {
'mapVisible' : false,
'showHostile' : false,
'showAlliance' : false,
'showBookmarks' : false
}
function custom_setValue(k,v){
GM_setValue(k,v);
}
function custom_getValue(k,dv){
return(GM_getValue(k,dv));
}
function custom_deleteValue(k){
GM_deleteValue(k);
}
function getSavedInfo(){
return(custom_getValue('ajaxparams',null));
}
function getSavedServerId(){
return(custom_getValue('sid'));
}
var e = document.createElement('div');
var idAttr = document.createAttribute('id');
var styleAttr = document.createAttribute('style');
idAttr.nodeValue = 'shadow_map_container';
styleAttr.nodeValue = 'background-color:white;top:150px;left:75px;position:absolute;height:600px;width:600px;';
e.setAttributeNode(idAttr);
e.setAttributeNode(styleAttr);
var c = '<strong>This is the map window.</strong>';
e.innerHTML = c;
document.body.appendChild(e);
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
}
function showHide()
{
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
Options.mapVisible = false;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
Options.mapVisible = true;
}
}
var btnStr = '<a class="navTab" target="_top" onclick="showHide();return false;" href="javascript:void(0)"><span>Shadow Mapper</span></a>';
var myNavContainer = document.getElementById('main_engagement_tabs');
var inner = myNavContainer.innerHTML;
var newStr = btnStr + inner;
myNavContainer.innerHTML = newStr;
This is not a z-index problem, it's a coding style and event-listener problem.
You cannot activate a button that way in a Greasemonkey script. showHide() resides in the GM sandbox, the page's JS cannot reach it from an onclick.
(One more, of many, reasons why inline JS should be avoided.)
In this example, you would activate the link like so:
function showHide()
{
if(Options.mapVisible == true)
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_UNDER;
Options.mapVisible = false;
}
else
{
document.getElementById('shadow_map_container').style.zIndex = ZINDEX_OVER;
Options.mapVisible = true;
}
return false;
}
var btnStr = '<a class="navTab" target="_top"><span>Shadow Mapper</span></a>';
var myNavContainer = document.getElementById('main_engagement_tabs');
var inner = myNavContainer.innerHTML;
var newStr = btnStr + inner;
myNavContainer.innerHTML = newStr;
var btn = document.querySelector (".main_engagement_tabs > a.navTab");
btn.addEventListener ("click", showHide, true);

Categories

Resources