Get element under mouse on click - javascript

I am building a Chrome extension and my goal is the following:
Once a user Ctrl clicks on a username on Reddit, I would like to capture that username on my content script page and send it over to my background page.
Here is how the html in reddit looks like for a random user, the class name is not consistent, so i can not use that.
<a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse86">u/strasse86</a>
So far I have being experimenting with the onmouseover just trying to capture the username but without success, since it always returns the first captured result.
window.onmouseover=function(e) {
var href = document.getElementsByClassName(e.target.className[i].href);
if ( typeof href != "undefined") {
if (href.includes("https://www.reddit.com/user/")){
// do more actions..
}
}
};
Any ideas please ?

I'm not sure if this is going to help but this is at least something you can look at.
window.onmouseover=function(e) {
var href = e.target.href;
if ( href) {
if (href.includes("https://www.reddit.com/user/")){
console.log('Contains reddit');
} else {
console.log('Does not contain reddit');
}
}
};
<a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse86">u/strasse86</a>
<a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="/user/strasse87">u/strasse87</a>
<a class="s1vhwcq3-4 eTpNeg s1461iz-1 gWXVVu" href="https://www.reddit.com/user/strasse88">u/strasse88</a>

document.onclick = (e) => {
console.log(e.target.tagName)
}
Use document.onclick and e.target give the HTML element.
Related Answer: https://stackoverflow.com/a/75472142/12298205

Related

How can I avoid infinite loop when reformatting url hash with Jquery event 'hashchange'

Issue Background
I have set up my webpage to use identifiers with prefix #s- to differentiate anchor links from other page identifiers. The window.location.hash changes to hash which moves the frame to the content in focus but also triggers the hashchange listener causing a loop.
What I've tried
I have it working for whenever the hash has changed but the only instance it does not work is when the same link it pressed (as I use this in the condition to stop the infinite loop). The code for this was:
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
What I want
I'd like to be about to find a condition or method to allow users to select a link to change the hash but also allow them to re-select the same link as many times as they want without causing a loop.
JS
last_hash = ''
function manageHash() {
var hash = $(location).attr('hash');
if($('#s-'+hash.substring(1)).length != 0 && '#s-'+hash.substring(1) != '#s-' ) {
last_hash = hash
window.location.hash = '#s-'+hash.substring(1);
}
}
$(window).on('hashchange', function(e) {
if ($(location).attr('hash') != last_hash) {
manageHash()
}
});
$(document).ready(function() {
manageHash()
})
HTML
<div class="contentSubSectionContainer contentSubSection" id="s-{{ subsection.slug }}">
<h2 class="contentSubSectionFont1Bold">{{ subsection.sub_section_title }}:</h2>
<div class="contentSubSectionContentFont1">
{{ subsection.content_rendered|safe }}
</div>
</div>

Go to given url after checking condition

Arter clicking i need to run chkMethode() in javaScript and then I decide is it go to the url or not
When i clicked 'Go' it does not run chkMethode() directly go to the given link. what to do?
Go
It's because JavaScript needs to prevent the anchor from performing its usual event and it does this using preventDefault. Here, as best practice, I've separated out your JS from the HTML and used an id.
HTML
<a id="go" href="http://www.google.com">Go</a>
JS
var go = document.getElementById('go');
go.onclick = chkMethode;
function chkMethode(e) {
e.preventDefault();
if (check) {
window.location.href = this.getAttribute('href');
}
}
function chkMethode(event)
{
if (<<certain condition>>)
{
event.preventDefault();
return false;
}
}
Go
<a onclick="event.preventDefault();chkMethode();" href="http://www.google.com" > Go </a>
Function chkMethode () {
Var valuetochck = // value to be checked
If(valuetochck == "")
{
Window.location.href="url1";
}
Else
{
Window.location.href="url2";
}
}

iScroll url hash change support

This is a known issue for iScroll and it only seems to happen in iOS5 where the menu completely stops working. All my sub links in iScroll are hash anchors. Does anyone have a workaround for this?
The way I handled it was to hijack the anchor links themselves and replace them with scrollToElement calls instead.
// Hijack hash anchors and scroll to them
$('a').click ( function (e) {
var id = $(this).attr('href');
if (id.substr(0,1) == '#') {
e.preventDefault();
setTimeout( function() {
scroller.scrollToElement ( id, 0 );
}, 0);
return false;
} else {
return true;
}
});
This code should only hijack links that begin with #. It then handles the scrollToElement in a setTimeout which fixes some other intermittent bugs. It works well on my end as long as your anchors are properly named with id's. If you are using name attributes instead of id attributes, you'll need to rewrite these.
This code will copy name attributes and put them in the id attribute if it is blank. You probably won't need this, though.
$('a').each (function (i, e) {
var n = $(e).attr('name');
var id = $(e).attr('id');
if ( typeof id == 'undefined' || id === null || id === '') {
$(e).attr('id', n);
}
});

double click event for div

I am trying to add an event handler to a div that has an image inside of the div. My problem is that the event only works if you double click outside the div right next to it. When you double click the picture inside the div it doesnt not trigger the event. How do I make it so that the event works both ways?
html
<div id="placeholder">
<a href="http://google.com" target="_blank">
<img src="http://www.fat-animals.com/wp-content/uploads/2009/03/11.jpg" alt="" />
</a>
</div>
javascript
var pic;
pic = document.getElementById("placeholder");
pic.ondblclick = function() {
pic.innerHTML = "blocked!";
}
demo
http://jsfiddle.net/9DWrN/
check this fiddle
http://jsfiddle.net/unloco/9DWrN/3/
var pic = document.getElementById("placeholder");
var clicked = false;
pic.onclick = function() {
if(clicked) {
pic.innerHTML = "blocked!";
} else {
clicked = true;
}
setTimeout(function(){
clicked = false
}, 333); //detect fast clicks (333ms)
}​
Your current solution actually works, it just doesn't seem like it, since you are redirected to a new page.
If you have Chrome (Firefox too probably, maybe even IE 8+), double middle click on the image (opens in new tab/window). Your event will still get fired. You can then proceed to preventDefault on these events.
Using a double click event is not the best idea to prevent malicious clicks though, as the double click event will only get thrown every two clicks. While a client side validation is bad to prevent malicious clicks anyways, its best to use a click event and check with a timer (i.e. throttle the event to a maxmimum of once every 200 milliseconds, or only allow it if there was not a previous click within the previous 200 milliseconds.
And what about changing pic.innerHTML at onclick?
See http://jsfiddle.net/4Kecd/
var = document.getElementById("placeholder");
pic.onclick = function() {
pic.innerHTML = "blocked!";
alert('The link has been blocked');
}
Even if you delete the link, it will be followed that time.
See http://jsfiddle.net/4Kecd/1/ too.
You can do...
var pic1 = document.getElementById("placeholder1"),
clicked1=false;
pic1.onclick = function() {
if(clicked1){
alert("The link has been deleted. You can't follow the link twice!");
}else{
pic1.innerHTML = pic2.getElementsByTagName('a')[0].innerHTML;
alert('The link has been deleted.\nHowever, the new tab will be opened when you accept this alert.');
clicked1=true;
}
}
...if you want to delete the link but you want the image.
Or you can just disable the link:
var pic2 = document.getElementById("placeholder2"),
clicked2=false;
pic2.onclick = function(e) {
var a=pic2.getElementsByTagName('a')[0];
if(clicked2){
alert("The link has been disabled. You can't follow the link twice!");
a.href="#";/* Nonsense since we have disabled the link,
but we want to ensure that the link isn't followed*/
}else{
clicked2=true;
a.onclick=function(){return false;}
alert('The link has been disabled.\nHowever, the new tab will be opened when you accept this alert.');
}
}
Note: UnLoCo's solution is good but its problem is that it doesn't prevent us from following the link.
Instead, you can disable the link at first click and enable it after some seconds:
var pic = document.getElementById("placeholder"),
clicked=false;
pic.onclick = function(e) {
var a=pic.getElementsByTagName('a')[0];
if(clicked){
alert("The link has been disabled. You can't follow the link twice!");
a.href="#";
}else{
clicked=true;
a.onclick=function(){return false;}
if(!a.getAttribute('data-href')){
a.setAttribute('data-href',a.href);
}
alert('The link has been disabled.\nHowever, the new tab will be opened when you accept this alert.');
setTimeout(function(){enableLink(a);},5000);
}
}
function enableLink(a){
a.href=a.getAttribute('data-href');
a.onclick=function(){return true;}
clicked=false;
}
See it here: http://jsfiddle.net/4Kecd/2/

Problem with event.target in IE

I'm writing js for a status update system to be used on various pages throughout a app that I'm working. I am really just starting to get more comfortable with javascript so it has been somewhat of a challenge to get to the point where I have everything now.
The status system is basically a facebook clone. For the most part everything is supposed to function the way that facebook's status updates and status comments do. The intended behavior is that when the user clicks in the status textarea, the div under the status textarea slides out revealing the submit button as well as some other checkboxes.
If the user clicks anywhere else on the page except a link or any element that has the class prevent_slideup the div slides up hiding the submit button and any checkboxes.
I'm using a document.body click function to determine what the user clicked on so I know which form elements to hide if I should even hide them. I do not want this slideup to take place on a textarea if that textarea has focus or the user is selecting a checkbox that goes with that form. Hence the prevent_slideup class. I also do not want to bother running the slideup logic if the user has clicked on a link. I'd prefer they just leave the page without having to wait for the animation.
The code that I was using to accomplish this task can be found in the $(document.body).click(function (e) section below where I'm doing a .is('a') check on the event target.
This code works as expected in chrome and firefox, however in ie when a link is clicked for the first time it seems that the element stored in var target is actually a div instead of an anchor. What ends up happening is that the submit div slides up and the user is not taken to the link that they just clicked on. If a link is clicked a second time the user is taken to the page as you would expect.
It seems to me that there's some kind of a lag in ie as to what the current event being fired is.
The entire status module is working other than this one strange ie bug regarding the users click on the link not being carried out the first time that they click a link after opening the status textarea. Does anything jump out in this script that would explain this behavior or does anyone have any other advice?
Thanks in advance for your help.
$(document).ready(function(){
$("textarea.autoresize").autoResize();
});
$(document.body).click(function (e){
var target = e.target || e.srcElement;
console.log(target);
console.log($(target).is('a'));
if($(target).hasClass('prevent_slideup') || $(target).is('a'))
{
return true;
}
else
{
var active_element = document.activeElement;
var active_status_id = $(active_element).attr('data-status_id');
var active_has_data_status_id = (typeof active_status_id !== 'undefined' && active_status_id !== false) ? true : false;
$('textarea').each(function(){
if($(this).hasClass('status_comment_textarea'))
{
var status_id = $(this).attr('data-status_id');
if($('#comment_textarea_'+status_id).val() === '' && (!active_has_data_status_id || active_status_id !== status_id))
{
hide_status_comment_submit(status_id);
}
}
else if($(this).attr('id') === 'status_textarea')
{
if($('#status_textarea').val() === '' && $(active_element).attr('id') !== 'status_textarea')
{
$('#status_textarea').html($("#status_textarea").attr('placeholder'));
hide_status_submit();
}
}
});
return true;
}
});
$("#status_textarea").live('click', function(){
if($('#status_textarea').val() === $("#status_textarea").attr('placeholder'))
{
$('#status_textarea').html('');
}
show_status_submit();
return false;
});
$(".comment_toggle").live('click', function(){
var status_id = $(this).attr('data-status_id');
show_status_comment_submit(status_id);
return false;
});
$(".status_comment_submit").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_comment_submit_wrapper_'+status_id).addClass('status_comment_submit_successful');
return false;
});
$(".show_hidden_comments").live('click', function(){
var status_id = $(this).attr('data-status_id');
$('#status_hidden_comments_'+status_id).show();
$(this).hide();
return false;
});
function hide_status_submit()
{
$("#status_textarea").removeAttr('style');
$("#status_textarea").blur();
$("#status_block").removeClass('padding_b10');
$("#status_submit_wrapper").slideUp("fast");
return false;
}
function show_status_submit()
{
if ($("#status_submit_wrapper").is(":hidden"))
{
$("#status_block").addClass('padding_b10');
$("#status_submit_wrapper").slideDown('fast');
}
return false;
}
function hide_status_comment_submit(status_id)
{
if(!$('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#status_comment_submit_wrapper_'+status_id).hide();
$('#fake_comment_input_'+status_id).show();
$('#comment_textarea_'+status_id).removeAttr('style');
}
return false;
}
function show_status_comment_submit(status_id)
{
if($('#status_comment_submit_wrapper_'+status_id).is(":hidden"))
{
$('#fake_comment_input_'+status_id).hide();
$('#status_comment_submit_wrapper_'+status_id).show();
$('#comment_textarea_'+status_id).focus();
}
return false;
}
function status_comment_submit_successful()
{
hide_status_comment_submit($('.status_comment_submit_successful').attr('data-status_id'));
$('.status_comment_submit_successful').removeClass('status_comment_submit_successful');
return false;
}
I figured out that there were two main issues with my script...
1.) The document.body function and the #status_textarea live click funtioins were conflicting with each other.
2.) After adding the logic for the #status_textarea function into the document.body function I noticed that the script still didn't quite work as expected in internet explorer unless I had an alert in the function. The problem at this point was that the autoresize plugin that I'm using on the textarea was also conflicting with the document.body function.
I was able to rectify the situation by adding a dummy text input and hiding the status textarea. On click of the dummy text input the status textarea is shown and the the dummy text input is hidden. I have no idea why this worked, but it seems to have solved my problems.

Categories