Html onmousedown vs href Precedence - javascript

I use the following code in one of my html pages.
When user clicks "Search Engines" links it opens yahoo.com on a new page and Google on current page.
I've tested this and it works (opens both urls), but is there any chance that the page will complete the window.location (redirect to a different page) without completing the href command?
Is there a rule for Precedence between the two command?
**Note: I know I can solve the problem in different ways, but I'm curious about this specific situation.
<html>
<head>
<title></title>
<script type="text/javascript">
function clickRedirect() {
window.location = 'http://www.google.com';
}
</script>
<body>
<a onmousedown="clickRedirect()" href="http://www.yahoo.com" target="_blank">Search Engines</a>
</body>
</html>

The mousedown event will happen first, but as you can see from the fact your code is currently working, that's not the whole story.
The question is: Once the mousedown has happened and you've set window.location, does the page get whisked away immediately (and therefore processing of the default action of the click on the a element doesn't happen), or does that default action get completed before the page is destroyed and replaced with the new page?
The answer is: I don't think that's guaranteed behavior at all (either way), and I wouldn't rely on it cross-browser. For one thing, what if the user holds down the mouse button? Since the default action of an a element isn't triggered until a click, which requires a mouseup.
Instead, I'd probably hedge my bets, in two ways:
First, I'd use click, not mousedown, for this. Users don't expect pages to swap out when they just hold the mouse down.
Second, I'd change your function:
function clickRedirect() {
setTimeout(function() {
window.location = "http://www.google.com";
}, 0);
}
Now you're specifically giving the browser a chance to complete the default action of the click before you go off to another page.
You might find more information on this buried deep in the DOM events specifications:
DOM2 Events
DOM3 Events
...in that they might say something about what should happen when an event is in progress and the page is being destroyed. I didn't immediately see anything.

Related

Is it arriving the javascript later than the html?

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

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.

Popstate with Hashtags?

I have a site that uses AJAX to dynamically load content into a div.
The links to do so are anchors with href="#" and an onclick event to trigger the AJAX.
This leaves me without a history when I click back, so if I load one page, then another and click back, it does nothing.
A basic version of the code is this:
<script type="text/javascript">
function loadXMLDoc(url)
{
<!-- Load XML Script here. -->
}
</script>
</head>
<body>
<div id="myDiv">
<!-- Target div. -->
</div>
Click Me.
Click Me.
Click Me.
</body>
What I would like to know is, can I give each link a different "#" and then use a popstate handler to call the appropriate event, so if I click link 1, 2 and then 3 and then start hitting the back button, it'll go back to 2 and then 1 etc..
I was going to use history.js and start using pushstate in the loadXML script but I think the whole manipulating history thing is a bit dirty and unreliable.
Am I thinking on the right lines or is there a better way?
Currently all my links just use "#" so that it pops back to the top of the page when loading more content but I'd like to be able to go back if possible.
Any help would be great.
Browser saves hashtags to history properly. Just add hashtag #1 to this question page, hit enter, change it to #2, hit enter, change it to #3, hit enter. Now click back button, and you'll see hash changes from #3 to #2. I recommend to change only hash itself on link click and react on page hash change and page load events.
function react() {
var hash = window.location.hash.replace("#", "");
loadXMLDoc(hash + ".txt");
};
document.body.onload = function() {
react();
window.onhashchange = react;
};
Click me
Click me
Click me
Please note that onhashchange event does not supported by old IE. The only way to deal with it if you want is to define timer with setInterval and check hashes equality.
Try to use combination of LocalStorage and HistoryAPI.
When you load XMLDoc store it in LocatStorage, when back is pressed - load data from storage, not from web.
A bit code above.
/* Handling history.back added */
window.onpopstate = function(event) {
yourHandleBackFunction(event.state);
};
function yourHandleBackFunction(renderTs) {
/*Check TS and load from localStorage if needed*/
};

Check if the webpage has been modified

I am working on chrome extension for facebook. If you use facebook, you know that when you scroll down to the bottom of the news feed/timeline/profile it shows more posts. The extension actually adds a button beside the "like" button. So I need to check if there are more posts to add that button to.
Right now to check if the page has been modified, I use setInterval(function(){},2000).
I want to run a function when the user clicks the button. But this function doesn't work if I put it outside (or even inside) setInterval() – The Koder just now edit
How can I check if the webpage has been modified WITHOUT using a loop?
Example:
$(document).ready(function(){
window.setInterval(function(){
$(".UIActionLinks").find(".dot").css('display','none');
$(".UIActionLinks").find(".taheles_link").css('display','none');
$(".miniActionList").find(".dot").css('display','none');
$(".miniActionList").find(".taheles_link").css('display','none');
//only this function doesn't work:
$(".taheles_link").click(function(){
$(".taheles_default_message").hide();
$(".taheles_saving_message").show();
});
//end
$(".like_link").after('<span class="dot"> · </span><button class="taheles_link stat_elem as_link" title="תגיד תכל´ס" type="submit" name="taheles" onclick="apply_taheles()" data-ft="{"tn":">","type":22}"><span class="taheles_default_message">תכל´ס</span><span class="taheles_saving_message">לא תכלס</span></button>');
$(".taheles_saving_message").hide();
}, 2000);
});
In the future, this extension will use AJAX, so setInterval() can make even more problems for me.
If I understand correctly you want to get a notification when the page's DOM changes. And you want to do this without using the setInterval() function.
As your problem lies within the attaching event handlers to elements that are created after the page has loaded, you might be interested in checking out the jquery.live event attachment technique. I think it will solve your issue.
In general you want the page to throw a mutation event. There is a mutation event spec that might be what you're looking for. Here are some links that might be useful.
http://tobiasz123.wordpress.com/2009/01/19/utilizing-mutation-events-for-automatic-and-persistent-event-attaching/
Detect element content changes with jQuery
$(document).ready(function(){
setInterval('fun()',5000);
fun();
});
function fun()
{
alert(11)
}

Global Javascript link handler

Here's what I have:
A web application that runs in a single HTML page (call it myapp.req), with content coming and going via AJAX
The application can be entered externally with a link such as myapp.req?id=123, and the application opens a tab with the item at id 123
The content on the page is mostly user's content, and many times has inner-application links to myapp.req?id=123
The problem is that clicking a link to myapp.req?id=123 reloads the browser, and removes any content or state that the user had loaded
What I want is to be able to catch link clicks whose destination is myapp.req?id=123, and instead of reloading the page, just open the tab for item 123, leaving anything else currently loaded alone. If the link is for an external website, though, obviously just let the browser leave.
So my question really: Can I have a global link handler that checks if I want to handle the link click, and if so, run some Javascript and don't leave?
I understand I could find all <a>s and add listeners, but my hope is that the solution would only require setting up the listener once, and not adding link handlers every time new content is loaded on the page. Since content can be loaded many different ways, it would be cumbersome to add code to all those places.
Does that make sense?
jQuery's live is what you need:
$('a').live("click", function () {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
Any link will now have this click handler whether it's been added after this is called or not.
Sure you can. Add a clickhandler on the body. So you catch all clicks. Then you have to check if the target of the event or one of its parent is a link with your specific href. In this case stop the event and open the tab.
updated to use .live instead of .click
If you use jQuery, you can add a "live" click event handler to every a href at once:
<body>
click here
<br/>
whatever
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$('a').live('click',function() {
var myID = $(this).attr('href').match(/id=([a-zA-Z0-9_-]*)\&?/)[1];
if (myID) {
//run code here
alert(myID);
return false;
}
});
</script>
This should extract the id from the href's query string and let you do whatever you want with it.

Categories