Is it arriving the javascript later than the html? - javascript

I'm trying to change the size of a pop-up and give it the same width than the screen, sent from an iframe.
var screen_width = parent.screen.width;
Then I got the html:
<a href="#" onClick="window.open('https://www.google.com','popup', 'width='"+screen_width+"',height=400px')">
I've tryed all possible convinations with the ' " or whatever I know, but I think it should work lie this.
Sorry if it's obvious, my coding skills are not so developed, but I think, it's possible, html it's loading before javascript?
P.D.: One more thing, I want to use a variable, because I want to change a bit the real size of the screen.

One problem you might be having is that in your window.open() options, you shouldn't specify px... just put the number for your height.
In any case, here's a better implementation of what you're trying to do. In your HTML:
<a href="http://example.com" target="_blank" data-fullpopup>Click me!</a>
This way, your link will work, and will even open in a new tab/window if your JavaScript doesn't run for some reason. This is a good fallback. The key here is the data-fullpopup attribute, which we'll look for in your JavaScript:
document.addEventListener('DOMContentLoaded', (e) => {
document.querySelector('body').addEventListener('click', (e) => {
if (!e.target.matches('a[data-fullpopup]')) {
return;
}
window.open(e.target.href, 'popup', 'width=' + window.screen.width + ',height=400');
e.preventDefault();
});
});
Basically, we wait for the document to fully load so that we can attach a click handler to the body element. (Note: If you're only doing this for a couple links, it's better to attach the click handler directly to them. I'm attaching it to body here, assuming that you'll have a lot of these sorts of links... it's more efficient to have one click handler in those cases. Remember though that then this click handler has to run for every click for any element on the page. Choose your tradeoff for your use case.)
Once the link is clicked, we confirm that it's a link with our data-fullpopup attribute. If it is, we treat it like a full-width popup. We get the target (the element) href on the fly, as well as the current screen width. Finally, we prevent the default action so that it also doesn't navigate to the page on its own.
https://jsfiddle.net/L5p0xk98/3/

As mentioned in the comments, you can do this without setting a variable first:
Click Me

Related

How to follow a link via swipe in javascript?

To handle swiping I use the script posted here:
http://padilicious.com/code/touchevents/
It works fine.
Now instead of changing the background (what the original script does), I would like it to grab the link contained within an <a> which has a class, and which is normally a link to the next page, but for mouse events like so:
<a href="mypage02.html" target="_self" class="NextP" title="My Second Page">
and then load the page.
I have many pages, with the same structure, I don't want to manually define the links. I want the js to get hold of the current href contained in the <a> and launch it, when triggered by the swipe. If possible.
Thank you ;-)
From what I understand, you want to look for a
<a href="http://example.com/" class="NextP">
element in a page (an <a> anchor tag with a NextP class), and when the user swipes, visit that link.
To do this, I would
look through your HTML for an a.NextP element, and capture its href attribute.
when the user swipes, set window.location.href to this attribute.
window.onload = function(){
var nextPageUrl = document.querySelector('a.NextP').href;
// just guessing how swiping works, I haven't looked through your library
document.body.onswiperight = function(){
window.location.href = nextPageUrl;
};
};
Of course, you would use the correct method of detecting the swipe.

Jquery - Targeting elements that have been changed after page load

I have not been able to find any discussion of what I'm struggling with on this site or any other, but perhaps I'm not asking the right question. I'm working on a web interface for a wireless speaker powered by the raspberry pi, and (as I inherited it) almost all the POST requests are done with calls to $.ajax. $().ready() is as follows:
$().ready(function (){
$(document).ajaxStart(function (){
$.blockUI({ message: '<img id="loadimg" src="img/loading.gif" width="64" />'});
}).ajaxStop($.unblockUI);
$("nav.setup-nav a").not("[target='_blank']").on("click", function (event){
event.preventDefault();
var href=$(this).attr('href');
$.ajax({
type:"POST",
url:href,
success:function (data){
$(".contentPanel").html(data);
$(this).blur();
$("html, body").animate({ scrollTop:100, scrollLeft:400}, 600);
},
});
return false;
});
});
Which forces all the content of the linked-to pages in the nav menu to load inside a div in the center of the page. That is, except for pages with target="_blank" attribute. This is so event.preventDefault and the UI blocking stuff doesn't get called when linking to an external page that we want to load in a new window. I'll try to concisely describe my issue: One of the menu items is (conditionally) a link to a web-based MPD client, which we definitely do NOT want to load inside a div on the same page, and thus has target="_blank" attribute. The problem is the user can also choose to enable or disable the MPD daemon through the web-interface. PHP handles the setting of all these kinds of state variables. Basically like this:
if ($config->is_flag_set($MPD_FLAG))
{
echo '<li><a target="_blank" id="mpd" href="rompr/">Local Playback Web Interface</a></li>';
}
else
{
echo '<li><a id="mpd" href="local-disabled.php">Local Playback Web Interface</a></li>';
}
and so when the page first loads, if the MPD daemon is not running the link to the web interface is pointed to a page that explains MPD is not enabled. This link does NOT contain the target="_blank" attribute. However, if one navigates to the settings form and switches on MPD, there is logic to replace the href and target attributes of that particular link, so theoretically all should work as if the page had loaded initially with the MPD flag on (if that is clear!). The problem is that when the "replaced" link with target="_blank" (set by .prop() or .attr(), I've tried both and it doesn't seem to make a difference) is clicked, the page still loads inside the div!I tried duplicating the click handler that's defined within $().ready and putting it in another function which I call after the link attributes are set, but it still doesn't work as I imagine it should! Just to verify that I wasn't crazy, I used .each() to print all the links that did and did not have the target="_blank" attribute and that all corresponds to what I believe it should be. Why is the replaced link not getting treated as if it has a target="_blank" attribute in the click handler? By the way, Going the other way and removing the target="_blank" attribute if MPD is turned off, works like a charm. Thanks so much in advance for any answers, and my apologies if I have duplicated a previous question!
Cheers,
Events are always tricky anytime you have to reload elements with ajax. The best way I've found is to attach the event to some container element that will not reload:
$('#always_present_container').on('click', "nav.setup-nav a", function (event){
if($(this).attr('target') != '_blank'){
...
}
});
that way the element is checked for the attribute when its container is clicked. When you set up $('element').click() the selector is checked on the page load and the events attached then, so when you reload something via ajax the new element doesn't get this event attached.
Note: normally you could avoid the conditional statement in the function, but I didn't know of an easy way to filter by target in a css selector.

How can I Detect when a Firefox WebPanel is closed?

I am interested in opening a webPanel on the right side of the Firefox window. Based on an MDN article, I determined that this could be done by setting the browser element's direction style. However, I wish to clear out this setting after the webPanel is closed. Is there a way I can detect this? Thus far, the only way I can think of is to poll sidebarWindow.location.href (to detect if the sidebar is changed) and sidebarHidden (to detect if the sidebar is closed).
var browser = document.getElementById('browser');
browser.style.direction = "rtl";
var sidebarWindow = document.getElementById("sidebar").contentWindow;
var sidebarBox = document.getElementById('sidebar-box');
var sidebarHidden = sidebarBox.collapsed || sidebarBox.hidden;
sidebarWindow.addEventListener("unload", function (event) {
alert("1"); //This code fires when the web panel is opened
//but not when it is closed.
});
sidebarBox.addEventListener("unload", function (event) {
alert("2"); //This code does not fire.
});
sidebarWindow.addEventListener("close", function (event) {
alert("3"); //This code does not fire.
});
sidebarBox.addEventListener("close", function (event) {
alert("4"); //This code does not fire.
});
openWebPanel('Test', 'http://www.google.com');
IIRC there are essentially three ways a sidebar can be "closed":
The user closes it using the GUI (X-box) or keyboard shortcut. In this case, the web panel will not necessarily get unloaded, so there is no unload event.
Another document is loaded into the web panel. In this case you might get an unload.
The user opens another panel. There is not necessarily an unload.
Should you go forward with your implementation, you need to make sure your code handles all three correctly.
and 3. should be observable by the <broadcaster id="viewWebPanelsSidebar"> changing the checked attribute (see the implementation of toggleSidebar()), so you could have another element observing and acting on onbroadcast.
should listen for unload and act accordingly.
To get proper unload events, I think the following should do the trick:
sidebar.contentDocument.getElementById("web-panels-browser")).
addEventListener("unload", ...);
But my memory there is a bit wonky, so you might need to fiddle with that a bit. (The sizebar has a <xul:browser id="web-panels-browser"> which displays the actual content...)
After having said all that: I think it is a bad idea to mess with the sidebar like this.
The MDN wiki(!) has bad advice in this case.
The sidebar was not designed to be messed with like this.
There are other add-ons "competing" with yours when it comes to messing with the sidebar.
The sidebar code is, for the most part, pretty archaic and under-maintained. Getting things like your requirement to work correctly is pretty hard. There still might be other code (in add-ons) that could dismiss the sidebar that you and I didn't think of.
The sidebar might not be the best place to display your content in the first place (what that content would be you didn't say). If it's something like context-help, dictionary/definition lookup results, login forms, then it won't be a good fit.
Some users might not like that their always-on bookmarks/history sidebar gets replaced by yours. You could handle this by re-opening the previous one, but that will only complicate matters further.
You might be better off using some other way to display information - e.g. a new tab, a panel, a new sidebar like the social sidebar... E.g the social sidebar is not only on the right, it actually is a standalone sidebar not part of the "main" sidebar.

Best way to distinguish links for internal action and ajax request?

Because this topic turn out to interdisciplinary (but still is about user experience) I'm curiuos what think about this an javacript developers.
My site handling a tags with href starting with # as ajax request. If request was successfully then it's change document hash to appropiate. Now I want to implement action links that call internal js function like going to site top, but I don't want javascript:myAction() reference, because most browsers is showing hint with referencing url when you're over the link. Probably I can use and successfully handle own url schema like action:myAction, but it's not enough solution - user was still hinted about magic url. Another option is using custom attribute like action="myAction" with href as custom string e.g. href="Go to top", but what with browsers compatibility? Last solution is to using a span styled as link to perfom action - user is not hinted about any url, but this is a part of link functionality what suggest that perform an action (going to url default).
What is better and why?
<script>
if(window.addEventListener)//Chrome, Firefox and Safari
document.getElementById('myLink').addEventListener('click',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
else//IE and Opera
document.getElementById('myLink').attachEvent('onclick',function(e){
var e = e || event;
e.preventDefault();
window.location = destiny;
});
</script>
Link
You should make your links work first without JavaScript. Then you don't have to worry about someone clicking <a href='/customers'>Customers!</a>. It works nicely and is accessible. Once you've reached this point you put the JavaScript on top to enhance the user experience. How you hook all of these up is up to you - say you want to handle deletes in a generic way, you might have links that look like this:
<a href='/customers/2' class='delete'>Delete customer</a>
<a href='/customers/2' data-action='delete'>Delete customer</a>
Or if it's specific per link, you set the id and wire it up that way:
<a href='/customers/2' id='delete'>Delete customer</a>
All of this wiring up should be done in an external JavaScript file.
I would do this by first writing everything in a way users without JS can use it, like
Go to top
Then I would take JS to enhance it immediatly after the DOM is loaded. First by adding the onclick event, then removing the href, to avoid any link hint (any other content than links probably not pass any validator) and finally a new style attribute that the cursor becomes a pointer on hover.
It is part of the very useful programmatic progressive enhancement structure. This way I get valid and compatible code as well as a comfortable behaviour.

Is this a good code to redirect parent window to a URL instead of the popup and close the popup?

This is the sample code:
in the pop up :
<body onunload='stopThisAndChangeParentInstead()' >
<a href='MY_URL'> Click here </a>
When the user clicks "Click here", the unload event fires which changes the URL
of the parent and closes this popup window.
function stopThisAndChangeParentInstead()
{
window.opener.top.location.href = "MY_URL";
window.close();
}
My questions:
What are disadvantages of using this method?
Are there any better ways to do the same thing?
Is there a JavaScript way to know to which URL the page is being redirected to? So that I can use that in body unload function, instead of mentioning MY_URL since I already know it.
I'd suggest using the target attribute on the link inside the popup to make the url open in the parent window (target="_parent" or target="_top" ought to work) and then use javascript only for closing the popup. it's a cleaner solution in my opinion.
instead of using an unload event, i'd recommend attaching an onclick event to the anchor tags directly. using jquery this would be:
$('a').click(function(){
window.opener.top.location.href = $(this).attr('href');
window.close();
return false;
});
although it's a somewhat, say, unusual way to set up navigation this way, i can't see any problems arising from this (aside from confusing the user, maybe)
The whole thing is a quite questionable way of creating a good user experience.
There are always better ways of doing one thing, you could write more beautiful code or write a smarter solution to the same problem. But in this matter, I think you should look at another user experience instead of coding the same experience in another way. Put the user first! Is it clear that the parent window is going to redirect? Ask these questions to a user that is not too keen on using computers, and the results might surprise you.
Yes, you can fetch the URL by doing:
.
<a id="myLink" href="http://myurl">
...
function stopThisAndChangeParentInstead()
{
var url = document.getElementById('myLink').href;
window.opener.top.location.href = url;
window.close();
}

Categories