Click handlers on links not working - javascript

I have a chrome extension in which I have
popup.html where I call jquery.js, popup.js and link.js
...
<script src="jquery.js"></script>
<script src="popup.js"></script>
<script src="link.js"></script>
</head>
popup.js
var streamGenerator = {
/* Twitch URL to the top 20 streams */
searchOnTwitch_: 'https://api.twitch.tv/kraken/streams?limit=20',
/* XHR Request to grab those streams */
requestStreams: function() {
var req = new XMLHttpRequest();
req.open("GET", this.searchOnTwitch_, true);
req.onload = this.showStreams_;
req.send(null);
},
/* onload event inserting the streams into the DOM */
showStreams_: function(e) {
var streams = JSON.parse(e.target.responseText).streams;
for (var i=0; i < streams.length; i++) {
var stream = {
game: streams[i].game,
name: streams[i].channel.name,
viewers: streams[i].viewers,
link: streams[i].channel.url,
};
$('tbody').append('<tr>'
+ '<td>' + stream.game + '</td>'
+ '<td>' + '<a href=' + stream.link + '>' + stream.name + '</a></td>'
+ '<td>' + stream.viewers + '</td></a>'
);
}
}
};
document.addEventListener('DOMContentLoaded', function() {
streamGenerator.requestStreams();
});
and then link.js
$(function() {
$('a').click(function(){
chrome.tabs.create({url: $(this).attr('href')});
});
})
The popup works and show what it is supposed to show, but the links don't open a new tab.
If I go to chrome's console, I don't get any error, but if I copy/paste the link.js jquery, the links work after;
What am I doing wrong?!

Your code loads popup.js before link.js. The relevant parts are executed in the following order:
// popup.js
$(function() {
$('a').click( ... );
})
// link.js
document.addEventListener('DOMContentLoaded', function() {
streamGenerator.requestStreams(); //<-- Creates the links
});
$(func) is roughly equal to document.addEventListener('DOMContentLoaded', func), so what you're doing is actually something like:
// Run after the DOMContentLoaded "domready" event:
$('a').click(...);
streamGenerator.requestStreams(); // Creates the links
First, you're binding the click event to all existing anchors (none). Hereafter you're adding the new links. This sequence is obviously not going to work.
It can be solved by swapping the order of popup.js and link.js, or by using event delegation:
$(document).on('click', 'a', function() {
chrome.tabs.create({url: this.href});
});

Related

How to conditionally open a new window/tab from an anchor tag?

I have the following code that will open a new tab/window and display the contents of a file based on a user clicking a button in a grid.
$(myButton).attr('href', '/MyController/GetDoc?Field1=' + dataItem.data1 + '&Field2=' + dataItem.data2);
$(myButton).attr('target', '_blank');
In the controller I return
return new FileContentResult(Convert.FromBase64String(myDoc), "application/pdf");
Everything works fine if I have a document.
How can I prevent the event from occurring if the controller method errors out or no document was found?
UPDATE:
$(function () {
$(".myButtonClass").each(function () {
var button = $(this);
var docUrl = '';
button.attr('target', '_blank');
checkDocumentUrl(button, docUrl);
});
});
In my button click method:
var myButton = $(e.currentTarget).closest(".myButtonClass");
$(myButton).attr('href', '/MyContoller/GetDoc?Field1=' + dataItem.data1+ '&Field2=' + dataItem.data2);
Before the button is clicked, request the document from the server. If that fails, the document does not exist, and you can disable the button through JavaScript.
Your controller should check if the document exists, and return HTTP 404 if it does not.
//Example data only. Each button presumably has its own data.
var dataItem = {
data1: 'foo',
data2: 'bar'
};
$(document).ready(function() {
//Check the url for each button
$('.myButton').each(function() {
var button = $(this);
var docUrl = '/MyController/GetDoc?Field1=' + dataItem.data1 + '&Field2=' + dataItem.data2;
button.attr('href', docUrl);
button.attr('target', '_blank');
checkDocumentUrl(button, docUrl);
});
function checkDocumentUrl(button, docUrl) {
//Make a request for the document
$.ajax({
method: 'HEAD',
url: docUrl,
error: function() {
//If request fails, document does not exist
handleInvalidDocument(button, docUrl);
}
});
}
function handleInvalidDocument(button, docUrl) {
button.on('click', function(e) {
//Prevent the link from opening a new tab
e.preventDefault();
alert('Sorry, no document available at ' + docUrl);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="myButton">My Button</a>

Dynamically adding multiple events to multiple webviews

Im new to using Electron and also kinda new to using the webview tag, so I pre-apologize for maybe not knowing something really obvious.
Im trying to dynamiclly create web views and add the following events to them.
did-start-loading
did-stop-loading
did-finish-load
page-title-updated
dom-ready
Im using a mix of Jquery and pure javascript to do this but currently im not having much luck. I have attached my code below so you can try find anything obvious there. Im not getting any javascript errors in the debug menu but at the same time none of it seems to be working.
function AddTab(URL){
tabcount++;
var NewTab = '<li href="#content-' + tabcount + '" id="tab' + tabcount + '" class="current"><img src="System_Assets/icons/Logo.png" /><span>Tab Home</span><a class="TabClose" href="#"></a></li>';
var NewContent = '<div id="content-' + tabcount + '" class="ContentHolder" style="display:block;"><webview id="webview-content-' + tabcount + '" src="http://www.ohhaibrowser.com"></webview></div>';
ChangeCurrent("");
//Hide current tabs
$(".ContentHolder").css("display", "none");
//Show new tab
$("#tabs-menu").append(NewTab);
$("#BrowserWin").append(NewContent);
$("#CurWebWin").val("webview-content-" + tabcount);
AddListeners("webview-content-" + tabcount,"tab" + tabcount);
UpdateTabCount();
}
function UpdateTabCount(){
$("#HideShow").text(tabcount);
}
function AddListeners(webview,tabid)
{
element = document.getElementById(webview);
element.addEventListener("did-start-loading", function() {
loadstart(tabid);
});
element.addEventListener("did-stop-loading", function() {
loadstop(tabid,webview);
});
element.addEventListener("did-finish-load", function() {
loadstop(tabid,webview);
});
element.addEventListener("page-title-updated", function() {
loadstop(tabid,webview);
});
element.addEventListener("dom-ready", function() {
domloaded(tabid,webview);
});
}
function loadstart(tabid)
{
$("#" + tabid + " span").val('Loading...');
//$("#" + tabid + " img")
}
function loadstop(tabid, webview)
{
$("#" + tabid + " span").val('');
}
function domloaded(tabid, webview)
{
element = document.getElementById(webview);
$("#" + tabid + " span").val(element.getURL());
}
You have to set Preload call to make change in Webview
browser.html
<script src="browser.js"></script>
<webview src="https://www.google.com/watch?v=1osdnKzj-1k" preload="./inject.js" style="width:640px; height:480px"></webview>
create sample js file name called inject.js
inject.js
__myInjection={
onloada : function() {
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
$("#header").html('<h1>Sample work</h1>\
<p>Hello, Google</p>\
Click me');
document.body.appendChild(script);
}
}
now in browser.js
onload = function() {
var webview = document.querySelector('webview');
webview.addEventListener("dom-ready", function(){
webview.executeJavaScript('__myInjection.onloada ()')
// webview.openDevTools();
});
doLayout();

Javascript Magento Create Account Preference Error

I am trying to create a second action on the Create New User Account form on Magento 1.9CE. We need an additional action to build an HTTP string and send to a URL as configured. So far we have built a script to pick up the fields, but this javascript isn't processing because the VarienForm is attached the event handler on document load. Could anybody shed some light on this code we have as to why its not processing?
<script type="text/javascript">
$(document).ready(function() {
window.setTimeout(function() {
$('#form-validate').on('submit', function( e )
{
var elements = this.elements;
e.preventDefault();
e.stopPropagation();
var subscribed = elements.is_subscribed.checked ? "y" : '';
var bglink = "http://suite9.emarsys.net/u/register_bg.php?owner_id=428212131&f=1481&key_id=3&optin=" + subscribed + "&inp_1=" + elements.firstname.value + "&inp_2=" + elements.lastname.value + "&inp_3=" + elements.email_address.value + "&inp_4=" + elements.year.value + "-" + elements.month.value + "-" + elements.day.value;
var img = $('<img width="1" height="1" src="'+bglink+'">')
.on('load error', $.proxy(function()
{
HTMLFormElement.prototype.submit.apply(this);
}, this))
.appendTo(this);
return false;
});
}, 2000);
});
</script>
If you are using jquery in your website may be jquery and prototype are conflict, to fix it:
- first of all you shoud add jQuery.noConflict(); to your website
- the second replace $ equal jQuery
ex:jQuery(document).ready(function() { })

jQuery animation order before/after load

I am trying to slide my main container #main up before loading the new content inside and then slide down again when the load is complete. This seems to work on the first click but on subsequent clicks the content loads instantly before the slideUp and slideDown animations begin.
$("#access a").address(function() {
$("div#main").slideUp(1111).delay(1200).load($(this).attr('href') + ' #menudropdown, #contentbody', function(){
$("div#main").slideDown(1111);
});
var current = location.protocol + '//' + location.hostname + location.pathname;
if (base + '/' != current) {
var diff = current.replace(base, '');
location = base + '/#' + diff;
}
});
Have you tried:
$("#access a").address(function() {
var mainDiv = $("div#main");
var loadLink = $(this).attr('href');
mainDiv.slideUp(1111,function(){
mainDiv.load( loadLink + ' #menudropdown, #contentbody', function(){
mainDiv.slideDown(1111);
});
});
// your other code
});
Have you tried the ready event on slideUp?
$("div#main").slideUp(1111, function () {
$(this).load($("#access a").attr('href') + ' #menudropdown, #contentbody', function(){
$("div#main").slideDown(1111);
});
});
Also I would suggest to hide the content before loading by using the full ajax function:
$.ajax({
url: $("#access a").attr('href'),
success: function (data) {
$("div#main").slideUp(function () {
$(this).hide().empty().append(data.find('#menudropdown, #contentbody')).slideDown();
});
}
});

redirecting to other page with value in javascript via click

I want to create a Javascript file to do these operations:
Pass the current link to the other page
Click on hypertext or image that is created dynamically in JavaScript file to redirect
Just I want to have a Javascript link in the html body and not other thing same this :
<div>
<script type="text/javascript" src="JScript.js"></script>
</div>
And in the JavaScript file I have these:
var DivTag = document.createElement("Div");
DivTag.setAttribute('ID', 'MyDivTagID');
$(document).ready(function () {
$("$MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + window.location;
});
});
This is not working. Please help me.
Several issues
you never added the div to the page
you used $ instead of # to access the div by ID
you do not consistently use jQuery
Plain JS: DEMO HERE
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
DivTag.innerHTML="Click";
DivTag.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
document.body.appendChild(DivTag);
}
Using linked image:
window.onload=function () {
var DivTag = document.createElement("div");
DivTag.setAttribute('id', 'MyDivTagID');
var anchor = document.createElement("a");
anchor.href="#";
anchor.onclick = function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
}
var img = document.createElement("img");
img.src="image.gif";
img.style.border="0";
anchor.appendChild(img);
DivTag.appendChild(anchor);
document.body.appendChild(DivTag);
}
jQuery: DEMO HERE
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>');
$("#MyDivTagID").click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
A small change to the jQuery code from mplungjan:
Change:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
To:
$(document).ready(function () {
$('body').append('<div id="MyDivTagID">Click</div>').find('#MyDivTagID').click(function(e) {
window.location = "http://www.MyLink.com/?Url=" + escape(window.location.href);
});
});
If you output e.currentTarget from the anonymous click handler function you get body since the event handler was attached to the body in mplungjan's solution. All I did was add .find('#MyDivTagID') directly after the .append() function so the click handler gets attached to the div and not the body.

Categories

Resources