Problems creating close me link in javascript bookmarklet - javascript

I am trying to add a close me link to this function. The way this works, is you paste all of this code without newline characters into a bookmark and the bookmark brings up a blue box on the screen.
Here is what I have so far, the close me link I have created is the "eleCloseLink" node I created:
javascript:(
function(){
var pagebody = document.evaluate( '/html/body' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
if (pagebody != null) {
var node = document.createElement("DIV");
node.style.position="fixed";
node.style.color="white";
node.style.background="blue";
node.style.width="350px";
node.style.top="50px";
node.innerHTML = "<br>BLUE BOX<br>2<br>";
var box = pagebody.appendChild(node);
/* Creating close link here */
var eleCloseLink = document.createElement("a");
eleCloseLink.setAttribute('href', 'javascript:( function(){ node.parentNode.removeChild(node); })();');
eleCloseLink.innerHTML = 'close me';
box.appendChild(eleCloseLink);
}
})();
So far I have tried doing this about 10 differen't ways and none have succeeded. The most recent way is putting javascript:( function(){ node.parentNode.removeChild(node); })(); inside of a and that is not working either. I feel like this should be one of the most common things to code as I see them on websites often and therefore there should be a lot of information on it. My scenario may be a little more specific than most b/c the box I am creating is just a DIV element and I am essentially trying to delete the DIV element (i have tried using this as well) with my close me link. Please let me know if anyone has any suggestions on how to create this close me link.

To resolve this, I created a click event listener which called a function that removes the object. To accompany this, I added a id attribute to the DIV object I was trying to remove. When the click event is triggered, the close function then evaluates the div object with XPATH referencing by id attribute. I was then able to run a remove() method on that object.
End Snippet:
/*Create Link in box to close box*/
var eleCloseLink = document.createElement("a");
eleCloseLink.innerHTML = '|CLOSE|';
eleCloseLink.addEventListener("click", CloseBox, false);
eleCloseLink.background = 'red';
box.appendChild(eleCloseLink);
}
/*Function to close the box */
function CloseBox() {
document.evaluate( "//*[#id='thebox']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.remove(this);
}
Still not completely sure if I had to use "this" or not in the remove() method as I was calling the remove() method on the object itself. However this is now working.

Related

How can I select the innerHTML when right-clicking on an e-mail link?

I am creating a Chrome Extension similar to the "Search on Google" when you right click on a selected text. However, I need mine to also work when right clicking on a mailto: e-mail link. How can I select the innerHTML, to select the e-mail address, and pass this information onto the extension to be searched?
I managed to make it work with the selected text (when highlighting text on the website) and right-clicking, but not when right-clicking on a hyperlinked e-mail address.
for(var i=0; i<numentries; i++)
{
//alert(_all[i][3]);
if(_all[i][3])
{
_all[i][0] = chrome.contextMenus.create({"title": _all[i][1], "contexts":["selection", "link"], "onclick": searchOnClick});
//alert("Menuitem created");
}
else _all[i][0] = -1;
}
var ask_options = getItem("_askoptions")=="true"? true : false;
if(ask_options){
//show separator
chrome.contextMenus.create({"type": "separator", "contexts":["selection", "link"]});
//show the item for linking to extension options
chrome.contextMenus.create({"title": "Options", "contexts":["selection", "link"], "onclick": function(){chrome.tabs.create({"url":"options.html"});}});
}
}
function searchOnClick(info, tab)
{
var itemindex = 0;
for(var i=0; i<numentries; i++)
{
if(info.menuItemId == _all[i][0])
{
//alert(i);
itemindex = i;
}
}
var ask_fg = getItem("_askbg")=="true"? false : true;
var ask_next = getItem("_asknext")=="true"? true : false;
var index = 1000;
var targetURL = _all[itemindex][2].replace("TESTSEARCH", info.selectionText);
targetURL = targetURL.replace("%s", info.selectionText);
Right now, it's only searching for the selection. When I attempt to search for a e-mail address hyperlink, the searched word is "undefined".
I need to change "undefined" to the e-mail address in the hyperlink.
Here is what I need to happen: https://i.imgur.com/2qJrwmk.png
You need to add an event listener for the contextmenu.
Using the example cat gave, I created a quick jsfiddle:
https://jsfiddle.net/kds2Lze8/
The code below adds the event listener to the document and is triggered on right click. Using that event you can then get the source element and ultimately the innerHTML.
Hope it helps!
document.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert(ev.srcElement.innerHTML);
return false;
}, false);
I'm not sure about some of the Chrome-extension-specific stuff (and your snippet is giving an error that I had trouble debugging without your HTML markup), but I think this script will demonstrate how to do what you want.
Edit:
You did indeed say you wanted to know how to run the script in response to a right-click, but I omitted that part. Sorry about that. The revised version should clarify that. It logs the innerHTML of the clicked element (although not on left-clicks) if the element is an anchor whose href attribute starts with mailto:.
// Run the 'checkAnchorForEmail' function on non-primary click events
document.addEventListener("auxclick", checkAnchorForEmail);
function checkAnchorForEmail(event){ //'event' will be our local name for any event that triggers this function
// Refer to the event's target element as 'clickedElement'
let clickedElement = event.target;
// If the element was an anchor with an 'href' attribute...
if(clickedElement.tagName.toLowerCase() === "a" && clickedElement.href){
// Define a string to identify anchors with emails
let comparedString = "mailto:";
// Only respond if the href begins with that particular string
if(clickedElement.href.indexOf(comparedString) === 0){
// Now we know the user right-clicked* an `a` element with an email address and can act accordingly
console.log(clickedElement.innerHTML);
}
}
}
// *Note that the 'auxclick' event is triggered by any non-primary button click. To isolate right-clicks, the 'contextmenu' event may be useful.
test#google.com<br />
google docs<br />
test2#google.com
One other thing:
If you need to prevent the context menu from appearing until your script has completed its tasks, you can use event.preventDefault();, but then you would need to show the menu manually later. One way to do this is by firing the 'contextmenu' event on the target element.
It's possible that doing so would cause this script to run again, creating an infinite loop. If this happens, you might try calling the preventDefault method conditionally like this (untested):
function checkAnchorForEmail(event){
// The above code goes here...
// Now we know the user right-clicked* an `a` element with an email address and can act accordingly
if(event.target.dataset.ready != "true"){ // Check the data-ready attribute
// event.preventDefault();
// event.target.dataset.ready = "true" // Set the data-ready attribute
// Make your changes to the context menu here
}
else{
// The changes have already been made, so show the context menu here
// (maybe using a technique like the one in the link below)
}
}
Here is a suggestion for using the MouseEvent interface to open the context menu, as mentioned in the in-code comments.

Creating a new window that has a button in JavaScript

Hey Im trying to to learn JavaScript at the moment, and I want to be able to create a button on a page that I created in JavaScript, but it always adds the button to index.html instead. Please note I am running this off of WebStorm IDE and don't have a URL/ dont know what to put for window.open(____) because of that.
It successfully creates a new window saying "Hello", but there is no button.
var myWindow=window.open('');
myWindow.document.write('Hello');
var button=myWindow.document.createElement("newbutton");
button.onclick= function(){
alert("blabla");
};
var buttonParent= myWindow.document.getElementById("buttonParent");
buttonParent.appendChild(button)
It looks as though you're creating a new window called myWindow, and writing the text hello to it. However, the container with the id "buttonParent" does not reside within the new window, but rather the document that index.html is in.
Try this out:
var newDiv = document.createElement("div");
newDiv.id = "newButtonParent" //make sure you pick a unique id
myWindow.document.appendChild(newDiv);
var buttonParent= myWindow.document.getElementById("newButtonParent");
buttonParent.appendChild(button);
Edit: Fixed a typo. From:
var buttonParent= myWindow.document.getElementById("buttonParent");
to
var buttonParent= myWindow.document.getElementById("newButtonParent");
When was the element with the ID buttonParent created? If this is your entire snippet, you'd first need to create that element as well, otherwise .getElementById isn't going to find anything in the new window, meaning .appendChild won't work properly.
The other thing to note is that alert is a property of the window object, so just calling alert('!') will attach the alert the the main window. You need to call it as myWindow.alert('!') to have it fire on the new window.
Also, document.createElement takes a tag name, so if you want default button behaviour it should be
myWindow.document.createElement('button');
Here's a working example. I've set the background of the container element to red so you can see it is there.
DEMO - (Click the run button.)
var w = window.open(''),
button = w.document.createElement('button');
button.innerHTML = 'My Button';
button.addEventListener('click', function () {
w.alert('!');
});
var container = w.document.createElement('div');
container.id = 'buttonParent';
container.style.background = 'red';
w.document.body.appendChild(container);
container.appendChild(button);

setting onclick in javascript is not working

So I'm writing some function that is working with Facebook's API. I was previously setting the onclick attribute by taking the parent and saying something along the lines of parent.innerHTML += "<a onclick = 'test("+parameter+")'>Previous</a>" and that worked fine. But I wanted to make it safer and more to standard so it is styled as follows:
function myMethod(link){
...
FB.api(link, function(response){
...
if(value != null){
var prev = document.createElement("a");
prev.innerText = "previous";
prev.setAttribute("id", "previous");
//prev.onclick = function(){test(this);}; doesn't work here
document.getElementById("facebook-photos").appendChild(prev);
}
//some other code (loops and stuff) including this
for(...){
var container = document.createElement("div");
container.classList.add("container");
container.classList.add("thing");
container.onclick = function(){test(this);}; // works here
}
//
if(document.getElementById("previous")){
document.getElementById("previous").onclick = function(){test(this);}; //works here
}
}
}
yet for some reason whenever I try and use this, clicking the element does nothing. Inspecting the element shows no "onclick" field but displaying the element in the console shows that the onclick field is not null. Nothing is covering the element and I've tried it as a div and as a button. When I try and do document.getElementById("previous") earlier, it still doesn't work. Why does this happen? Is it just the asynchronous nature of Javascript? The assignment in the middle works even though its relatively soon after the creation of the element, but the one at the beginning does not.

How to create click button in pure JavaScript?

how to create click button in pure/native JavaScript without using any html tag and css? This button, when the user click it there's a confirmation box will appear then, when the user click the Ok option, there's a popup window will appear.
I have already code in popup window and confirmation box. Here:
if (confirm("Go?") == true) {
popupWindow = window.open('/filename.htm', "name", windowFeatures);
popupWindow.focus();
} else {
test1= "";
}
I want to display the click button under of:
<div class="activityHeaderPanel">
But, I don't have an access or privilege to change or edit the entire html.
Please help me. I'm not really a programmer. Thank you.
var test = document.getElementByClass("activityHeaderPanel");
function whatClicked(evt) {
alert(evt.target.id);
}
test.addEventListener("click", whatClicked, false);
You can use the native DOM API to create document nodes and attach events, using pure Javascript and no HTML.
var myDiv = document.createElement('div');
myDiv.className = 'activityHeaderPanel';
myDiv.onclick = function(){
if(confirm //...
}
To attach the div you created to the existing document you need to find its parent node and use appendChild:
//this will depend on your particular use case. For example, if the parent element is a
// <div id="theParent">
var parentNode = document.getElementById('theParent');
parentNode.appendChild(myDiv);

Jquery UI Dialog Remove Issue

Back from this issue
Multiple Dialog
I was able to solve the issue but now problem is that it removes the div so when I access that Div it give error. It gives error because when I open dialog it works fine after removing on close it gives e.rror
I don't want to removed jQuery('#divPopup') If there is only one div present. If multiple jQuery('#divPopup') are there remove() should be working fine.
jQuery('.register_button_class').live('click',function () {
var iFrameobj = createIframe('',iframeUrl);
jQuery('#divPopup').html(iFrameobj);
createDialogWithClose(url,'#bodyId');
return false;
});
Dummy Div for Dialog Popup, This get removed, when Click on Close Jquery Ui Popup.
So when I say
jQuery('#divPopup').html(iFrameobj);
It gives error.
<div id="divPopup"></div>
I'm assuming that your function:
createDialogWithClose(url, '#bodyId');
removes the div id="divPopup" each from the DOM when you close it.
I would suggest not initially including that div in your markup and change your function to create the div and append it to the DOM when it runs. Then remove like you're already doing.
jQuery('.register_button_class').live('click',function () {
var iFrameobj = createIframe('',iframeUrl);
jQuery("body").append("<div id='divPopup' />").html(iFrameobj);
createDialogWithClose(url,'#bodyId');
return false;
});
It's hard to tell what other issues you may be running into with this bit of code that you posted, however, jQuery("body").append("<div id='divPopup' />").html(iFrameobj); will create the divPopup each time the function runs. So, when you close it and it gets removed it will just get created again the next time that button is clicked.
EDIT: How to check if a Div exists -
if ($("#divPopup").length > 0){
// do something here
}
I solved like this
var length = jQuery('#divPopup').length;
if(length>1)
{
jQuery('#divPopup').dialog('destroy').remove();
}else
{
jQuery('#divPopup').dialog('destroy');
}

Categories