How to manipulate like button on Facebook web page? - javascript

I'm currently building a chrome extension and I'm trying to get it to be able to stop a like on Facebook from going through even after the like button has been clicked. In my content.js, I currently have the code:
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
element.addEventListener('click', function() {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel")
}
})
});
As of now, when the like button is clicked, a confirm box pops up but the like does not go through until "OK" or "Cancel" is clicked.
How do I prevent the like action from going through when the 'cancel' button is clicked? Thanks!

Try the following.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element)
{
element.addEventListener('click', function(e) {
var r = confirm("You clicked like");
if (r == true) {
alert("you clicked OK");
} else {
alert("you clicked Cancel");
e.preventDefault();
}
});
});
For reference : https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

You could try replacing the original function with a different function of your own.
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]')[0].onclick =
e => console.log('blablabla!')
document.querySelectorAll('a[data-testid="fb-ufi-likelink"]').forEach(function(element) {
let originalOnClick = element.onclick
element.onclick = null
element.addEventListener('click', function(e) {
console.log('look ma, no hands!')
originalOnClick(e)
})
})
Like
I tested it on Facebook and it works there too.
Obviously you have to adapt this concept to your needs.

You can use event.preventDefault()
Just add the parameter to your listener function
function(event){
...
event.preventDefault();
}

Related

Adding a click event to hide a popup

I have a popup with an id of myPopup.
show is a class that changes the display from none to block.
This is my first time using event handlers and I was looking to get some information on the different types and how to use them.
var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
}
var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
So first of all your if statement will only run once and since the class is only toggled during the function, then the if statement will never be run and so the event won't actually happen.
To fix this maybe try this approach:
var popup_v = document.getElementById("myPopup");
var trueorfalse = false;
function popup() {
if (trueorfalse === false) }
trueorfalse = true; // popup is there
popup_v.classList.toggle("show");
} else {
popup_v.classList.remove("show");
}
}
if(document.getElementById('myPopup').classList.contains("show")) {
document.addEventListener('click', function(event) {
popup_v.classList.remove("show");
});
OR
var popup_v = document.getElementById("myPopup");
function popup() {
popup_v.classList.toggle("show");
}
var trueorfalse = false;
document.addEventListener('click', function(event) {
if (trueorfalse === false) }
trueorfalse = true; // popup is there
popup_v.classList.toggle("show");
} else {
popup_v.classList.remove("show");
}
}
};
I did it these ways because the event listener just checks if the event is happening for how long the application (site) is run.
So you can just check if the class is there or not and then decide depending on that.
Tell me if anything is wrong.
I don't see a need to add the if condition specifically to check if it contains class and it it has remove it.
the toggle method should do both for you, i.e.
on toggle add show class,
on toggle again if show class is present remove it
check this example for reference - https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_class

bootstrap dropdown doesn't work as expected

I'm using dropdown functionality of bootstrap and I have this dropdown in container, but in outside I have wrapper, which is reacting on the same event (onclick), so I do
e.stopPropagation();
because I don't want to react on event in wrapper, when I'm clicking dropdown button. Unfortunately, this code also stops my dropdown event. Is it possible to avoid this behaviour and display only dropdown list, without alert?
https://jsfiddle.net/hms5265s/
Here is my solution.
document.querySelector('.container').addEventListener('click', (e) => {
if($(e.target).is("#dropdown")){
alert('work');
}
else{
e.stopPropagation();}
});
If you want your alert to be called on the click event of the wrapper but not the click event of the dropdown iteself you can try something like this
document.querySelector('#wrapper').addEventListener('click', (e) => {
var source = event.target || event.srcElement;
console.log(source.id);
if (source.id !== 'someId') {
// do some stuff
alert("I don't want this alert");
}
// you can stop the even propagation here if you want to.
});
Here is a JSFiddle
If you also don't want to assign an Id for your dropdown you can also check for a class.
here is my solution
Element.prototype.hasClass = function(className){
tClassName = this.className;
return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};
document.querySelector('#wrapper').addEventListener('click', (e) => {
console.log('clicked' + e.target.hasClass('dropdown-toggle'));
if(e.target.hasClass('dropdown-toggle')) return
alert("I don't want this alert");
});
document.querySelector('.dropdown-menu').addEventListener('click', (e) => {
e.stopPropagation();
});
https://jsfiddle.net/hms5265s/6/
updated solution:
Element.prototype.hasClass = function(className){
tClassName = this.className;
return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};
document.querySelector('#wrapper').addEventListener('click', (e) => {
if(e.target.hasClass('dropdown-toggle')) return
alert("I don't want this alert");
});
document.querySelector('.container').addEventListener('click', (e) => {
if(! e.target.hasClass('dropdown-toggle')){
e.stopPropagation();
}
});
https://jsfiddle.net/hms5265s/12/

Use a preventdefault to get out of the loop after pressing Enter key

This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})

How to prevent Bootbox from displaying twice after a double click?

I have a <ul> element that opens a bootbox when it's clicked. Double clicking this element triggers the onclick in JQuery twice
$("#email-list").on("click", ".list-group-item", function (e) {
bootbox.confirm("Send a forgotten password email to " + email + "?", function (result) {...}}
I tried using 'e.preventDefault()'
$(document).ready(function () {
$("#email-list").dblclick(function (e) {
e.preventDefault();
});
});
I even tried disabling clicking on the element but both failed. The bootbox still appears twice.
$("#email-list").bind('click', function () { return false; });
//...do stuff
$("#email-list").unbind('click');
Anyone has a suggestion?
Another solution can be to add:
bootbox.hideAll();
to hide any other bootboxes right before showing the bootbox like so:
bootbox.hideAll();
bootbox.confirm("Some Message " , function (result){/*do stuff*/}
Try this:
$("#email-list").on("click", ".list-group-item", function (e) {
if(!$('#myModal').is(':visible')){
$('#myModal').modal('show');
}
e.preventDefault();
}
Use the click event, then you can replace
e.preventDefault();
with
e.stopPropagation();
or
return false;
I figured the best way to do this is to separate the two events; onclick and dbclick, I used something like this, I hope it will save someone some time:
var DELAY = 700, clicks = 0, timer = null;
$(function () {
$("#email-list").on("click", ".list-group-item", function (e) {
clicks++; //count clicks
if (clicks == 1) {
//do stuff
clicks = 0; //after action performed, reset counter
}, DELAY);
} else {
clearTimeout(timer); //prevent single-click action
clicks = 0; //after action performed, reset counter
return false;
}
})
.on("dblclick", function (e) {
e.preventDefault(); //cancel system double-click event
});
}

A confirmation popup in JS

I am looking into making a confirmation menu in JavaScript to where it will run a set of code depending if you select yes or no.
Now I want it to happen on the window.onbeforeunload event but only when the individual presses "yes" do I want the rest of the code to work. If they press "no" I want the window.onbeforeunload to be cancelled outright. I am wondering if it is at all possible and how. Here is what I have so far. The reason why I want this is because when I run the script the popup shows up on return but before someone would get to choose to stay or leave. The click(); feature starts up erasing the information. I want the .click(); to start up after someone presses "yes" on the return and only if they press "yes".
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = document.getElementById("kioskform:broswerCloseSubmit");
var leave_safari = document.getElementById("kioskform:broswerCloseSafari");
function goodbye(e) {
if (!validNavigation) {
function disp_confirm()
{
var leaveMessage=confirm("Are you sure you want to leave")
if (leaveMessage==true)
{ if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//for IE
e.cancelBubble = true;
e.returnValue = leave_message.click();
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
leave_safari.click();
return '';
//add the code to delete the kiosk information here.
// this is what is to be done.
}
}
else
{
Alert("Returning to the page.")
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
jQuery('document').bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
jQuery("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
jQuery("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
jQuery("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function() {
wireUpEvents();
});
Why not just use window.confirm?

Categories

Resources