Unable to open link with jQuery click() - javascript

I want to open some relevant links after a button click by user. All these links have to open in a new tab.
I tried using the following code but it does not open the links:
$("div.relevant-links").on('click', function() {
var count = 0;
var relevant_links = $(this);
function open_link() {
if (count < relevant_links.siblings("a.sections").length) {
relevant_links.siblings("a.sections").eq(count).css({
background: 'yellowgreen'
});
relevant_links.siblings("a.sections").eq(count).click();
count++;
} else {
clearInterval(link_interval);
}
}
open_link();
var link_interval = setInterval(open_link, 5000);
});
All other code works fine because I can see the background color of the link change. However, the click() method does not seem to work.
How can I trigger the click on different links? All the links have to open in a new tab. I have set their target attributes to _blank.

First of all, remove the interval, if you're going recursive, use setTimeout, if there's even a minor flaw in your code you've got yourself an annoying memory leak.
Second, when you want to open a webpage, new tab or not. You'll need to do it right after a user initiated action like a click. If you're gonna trigger it again after 5 seconds it will get blocked in modern browsers.
Third, you could also retrieve the href of the links and perform a window.open('your href here', '_blank') instead of triggering the click event.
Last, don't open a bunch of "relevant" links. You're not making anyone happy with that. Especially not a new one every 5 seconds!

Related

Different links with target = _blank works only twice

I have a code that covers the whole content with a link (target= _blank), then turns that link's display into none, brings another link and so on.
In my browser everything works just fine but I got a complaint about how only 2 of these links work.
No matter which link they click, after the second one it doesn't work.
Did the same thing with addEventListener and onclick but they caused different problems so therefore I used "a href".
I only can use JavaScript to create these elements and unable to use plain HTML.
I searched about browser's behaviors on multiple new tab or window but couldn't find anything useful.
This is how I create the links:
var hidden= document.createElement("a");
hidden.href="somelink";
hidden.style.height="100%";
hidden.style.width="100%";
hidden.target="_blank";
hidden.style.display="none";
container.appendChild(hidden);
And to make them appear, I add an event listener to a video and make them appear and disappear the right time.
video.addEventListener("timeupdate",function () {
if(video.currentTime>=3 && video.currentTime<5){
hidden.style.display="block";
} else if(video.currentTime>=5 && video.currentTime<6) {
hidden.style.display="none";
}
}
Is it a browser behavior that blocks the multiple new tabs or should I look for the answer in something else in my code?

Can't simulate a click event with javascript in "web application"

I have searched a lot of information about this but have not found the solution yet.
My problem is the following, I am creating an extension to speed up the movement through several web pages, I have managed it with many of them, but I have come to some where I cannot simulate a click with Javascript and I don't know how to do it.
One of the pages is this: https://sports.betway.es/es/sports/in-play The page is in Spanish domain, therefore I do not know if they can access it from another country (without vpn), although I think that with domain ".com" it works.
The code is as follows, it's pretty simple.
var deportesActivos = document.getElementsByClassName("categoryListItemWrapper contentSelectorItemButton")
for(let i=0;i<deportesActivos.length;i++){
let nombre = deportesActivos[i].lastChild.firstChild.innerText
if(nombre == data.deporte){
deportesActivos[i].click()
}
}
deportesActivos I collect the DIV elements with that class from the page.
deportesActivos[i].lastChild.firstChild.innerText I extract the text of each element
if(nombre == data.deporte){
deportesActivos[i].click()
}
When it matches, click to enter the link.
The problem is that the click does not simulate me.
I have bought exactly the element that you click on, I have clicked manually and it works, I have tried to click on other elements of the web page and it does not work, I have tried to give a "listener on click" to the element and it does not work either.
The HTML of the page is as follows:Image with HTML Code of the website
I don't know if this helps but on website build with Ionic app neither works
The click event does not fully simulate a user click. It just fires the onClick handler on the element that you are targeting (and any parents).
If your are just redirecting to a new URL when the button is clicked, you could just do that in your loop instead.
// get the links, not the buttons
var deportesActivos = document.getElementsByClassName("categoryListItemWrapper contentSelector");
for (let i=0; i < deportesActivos.length; i++) {
// Drill down one extralevel to get the button text
let nombre = deportesActivos[i].firstChild.lastChild.firstChild.innerText;
if (nombre === data.deporte) {
// Redirect to the href in the link
window.location.href = deportesActivos[i].href;
}
}

Disable a link for couple of seconds

I'm making a book-website with a jQuery-plugin. Every time a link is clicked, the book-page switches to the next page and the .active class switches from link. The problem is that if you click fast between the pages, the active class switches but the movement of the book is too slow so you don't hop to the next page.
I'm trying disable the link after u clicked on one. My idea was just removing an attribute for a couple of seconds like this:
$('.button').click(function(e){
.. switch page using id
.. switch .active
$(".button li a").removeAttr("id");
}
So when the page is loaded, and the active class is switched. U cannot click on another link until the attribute is put back on.
How can remove an attribute for a couple of seconds? Or are there other options to disable a link for a period of time without removing the attribute?
An easy (but a bit hacky) way to accomplish this is returning early out of the handler if the action is already in progress:
var pageIsTurning = false;
$('.button').click(function(e){
if (pageIsTurning) { return; }
// do your stuff and change the page
}):
According to the docs of the booklet plugin you can bind to the bookletstart and bookletchange events which are where you'd update the pageIsTurning variable.
$(".selector").bind("bookletstart", function(event, data) {
pageIsTurning = true;
});
$(".selector").bind("bookletchange", function(event, data) {
pageIsTurning = false;
});
Note that this approach wouldn't work if you have more than one booklet on the page but could easily be adapted.

Title-changing effect/window event listener does not work

I tried to search but could not find out anything useful. This is a piece of code for my Greasemonkey script. Basically, I want to have the same effect as Gmail. When the page loads and you have new messages, the title will change repeatedly and make you notice. The problem is it does not work for the first time.
For example, if the user opens the page on new tab and does not move to the page, it does not work. But if the user moves to the tab and then moves to another tab, the script works.
Can anyone point me the right direction?
function startBlink(){
window.blinkInterval = setInterval(function(){
if(document.title != "Message"){document.title = "Message";}
else{document.title = "Application";}
} , 1000);
}
function blink(){
document.addEventListener("blur",function(){setTimeout(startBlink(),1000);},false);
document.addEventListener("focus",function(){clearInterval(window.blinkInterval);},false);
}
window.addEventListener("load",blink,false);
have you thought about changing (iterating through multiple variants of) window title instead of blinking (blur/focus)? that also attracts an eye.

Javascript : Change the function of the browser's back button

Is there a way to make the user's back button on their browser, call a javascript function instead of going back a page?
You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.
But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.
There are JavaScript libraries to help with this, with Really Simple History being a popular example.
yes, you can. Use this js:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.programadoresweb.net/");
},0);
}
}, false);
}(window, location));
That will redirect your back button to the location.replace you specify
I think this will do the trick.
you can write your custom code to execute on browser back button click inside onpopstate function.
This works in HTML5.
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
I assume you wish to create a one-page application that doesn't reload the website as the user navigates, and hence you want to negate the back button's native functionality and replace it with your own. This can also be useful in mobile web-apps where using the back button inside apps is common to close an in-app window for example. To achieve this without a library, you need to:
1st. Throughout your application modify the window's location.hash instead of the location.href (which is what tags will do by default). For example, your buttons could fire on click events that modify the location.hash like this:
button.addEventListener('click', function (event) {
// Prevent default behavior on <a> tags
event.preventDefault()
// Update how the application looks like
someFunction()
// Update the page's address without causing a reload
window.location.hash = '#page2'
})
Do this with every button or tag you have that would otherwise redirect to a different page and cause a reload.
2nd. Load this code so that you can run a function every time the page history changes (both back and forward). Instead of the switch that I used in this example, you can use an if and check for other states, even states and variables not related to location.hash. You can also replace any conditional altogether and just run a function every time the history changes.
window.onpopstate = function() {
switch(location.hash) {
case '#home':
backFromHome()
break
case '#login':
backFromLogin()
break
default:
defaultBackAnimation()
}
}
This will work until the user reaches the first page they opened from your website, then it will go back to new tab, or whatever website they were in before. This can't be prevented and the teams that develop browsers are patching hacks that allow this, if a user wants to exit your website by going back, they expect the browser to do that.
If you are creating a one-page web application, where your html body has different sections and you want to nevigate through back button to the previous section you were. This answer will help you.
Where your website sections are differentiated by #. Such as:
your-web-address.com/#section-name
Just follow a few steps:
Add a class and a id in every section in you html body. Here it is ".section"
<section class="section" id="section-name">...</section>
Add two CSS class in your linked css (e.g., style.css) file to your html (e.g., index.html) file such:
.section .hide {
display: none;
}
.section .active{
dislplay: block;
}
Add this JavaScript function in you linked .js (e.g., main.js) file to your html file.
window.onpopstate = function () {
if (location.hash !== "") {
const hash = location.hash;
// Deactivating existing active 'section'
document.querySelector(".section.active").classList.add("hide");
document.querySelector(".section.active").classList.remove("active");
// Activating new 'section'
document.querySelector(hash).classList.add("active");
document.querySelector(hash).classList.remove("hide");
}
}

Categories