JS redirect function - javascript

I am trying to create a function that changes the redirect link of a button if the url contains the word "TicketPreDateable".
So I have a button like this one:
<div class="col-12 col-md-6 col-xl-4" id="myproductid">
<figure class="effect-product mx-auto"><img class="figure-img img-fluid" src="myimage">
<figcaption><span class="badge badge-danger" style="top: -2.7em; background-color: red;">OFFRE SPÉCIALE</span>
<h2 class="mt-0" style="color: white !important;"><span>My </span>Product Title</h2>
<p>Profitez des pistes le samedi lorsque d'autres sont occupés à faire leurs valises ou coincés dans les bouchons. Un tarif unique à 24€ vous donne accès en toute liberté au domaine skiable pour la journée.</p>
<a onclick="produrlmobile("https://www.mylink.com/fr/ProductsNgTicket/ticketPreDateable?poolNr=13&projNr=495&ticketTypeNr=122&preDatable=True&groupId=1&Day=11&Month=12&Year=2021")" href=""></a>
</figcaption>
</figure>
</div>
And my function look like this :
function produrlmobile(produrl) {
if (produrl.includes("TicketPreDateable")) {
if (window.innerWidth < 960) {
window.location.href = produrl.replace(
"TicketPreDateable",
"TicketPreDateableMobile"
);
} else {
window.location.href = produrl;
}
} else {
window.location.href = produrl;
}
}
I have the impression that it is because of special characters in the url that the function does not work, but I do not know how to avoid that.
Thank you for your help and have a nice day !

See Sarens comment for issues with the HTML.
Also, note that the replace method is case sensitive. In your function it looks like you are trying to replace the string TicketPreDateable, but the url only contains ticketPreDateable.
I would recommend checking you are handling cases correctly, for both the old and new strings in the replace method arguments.

Related

Watir Click JS Button

I can't seem to get past a button in a landing page. Here is the JS element with parent nodes:
<div class="modal-body-content callfor-popup">
<h3>Welcome | Bienvenue</h3>
<p class="body_M_normal" aria-level="4" role="heading">Please select a language | Veuillez sélectionner une langue</p>
<div class="small_btn lcbo_cookie">
<a class="body_M_normal" href="https://www.lcbo.com/en/stores/store/redirect/___store/en/___from_store/en/uenc/aHR0cHM6Ly93d3cubGNiby5jb20vZW4v/">English</a>
</div>
<div class="small_btn lcbo_cookie">
<a class="body_M_normal" href="https://www.lcbo.com/en/stores/store/redirect/___store/fr/___from_store/en/uenc/aHR0cHM6Ly93d3cubGNiby5jb20vZnIv/">Français</a>
</div>
<hr>
<p class="caption_xxs_noletterspace">
You must be 19 years of age to purchase alcohol. Please note that we only deliver in Ontario / Vous devez avoir au moins 19 ans pour acheter de l'alcool. Veuillez noter que nous ne livrons pas à l'extérieur de l’Ontario.
</p>
</div>
This is what I am currently trying:
puts '1' if a.element(visible_text: 'English').exist?
puts '2' if a.link(visible_text: 'English').exist?
puts '3' if a.button(text: 'English').exist?
puts '4' if a.link(visible_text: 'English').exist?
puts '5' if a.element(visible_text: 'English').exist?
a.button(text: 'English').click
a.element(visible_text: 'English').click
a.link(visible_text: 'English').click
puts "clicks finished"
1, 2, 4 and 5 show up, indicating Watir knows they are there and exist. I can't seem to click that element though. It's not a formal HTML button, so that's why I'm trying several elements.
Is there a better way of dealing with such JS elements? I'm not sure how to focus on the English option.

element.click() is not emulating the click

document.querySelectorAll('button:nth-child(2)').click()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="Dialog ui-dialog-type-message" style="min-width: 300px;"><header><h1 class="dialog-title">Pile Nouveaux éléments pleine</h1></header><div class="dialog-body"><p class="dialog-msg">Vous ne pouvez pas acheter cet élément car vous avez 5 éléments ou plus dans votre pile d'éléments non attribués.</p><div class="ut-button-group"><button class=""><span class="btn-text">Annuler</span><span class="btn-subtext"></span></button><button class=""><span class="btn-text">M'y emmener</span><span class="btn-subtext"></span></button></div></div></section>
I'm making a chrome extension and i'm looking to click on the following button :
<button class=""><span class="btn-text">M'y emmener</span><span class="btn-subtext"></span></button>
On the console with query selector i've got the element :
document.querySelectorAll('button:nth-child(2)')[4]
It is the right button, every thing is good so far but when i add .click() after the element like so, the element doesn't get clicked either:
document.querySelectorAll('button:nth-child(2)')[4].click()
How can i get this to click on my button ?

Alert box to accept cookies in a web site

I wanna know how to put a .js code in a button that it's in a bootstrap alert that when the user clicked accept, the alert box no appear again.
Thanks a lot.
This is the code that I have, but doesn't work.
JS:
$(".btn_cerrar").on({
click: function(){
location.reload(
$(".pb-element-alert").hidden();
});
});
<div id="modal">
<p style="text-align: center;">Este sitio web emplea cookies para ofrecerle un servicio más</p>
<p> personalizado.</p>
<p style="text-align: center;">Si continúa navegando entenderemos que acepta nuestra</p>
<p style="text-align: center;"><a title="Politicas" href="images/eventos/POLITICA_DE_TRATAMIENTOS_DE_DATOS.pdf" target="_blank"><strong>Políticas de tratamiento de la información</strong></a> de nuestro sitio web.</p>
<button class=" btn_cerrar btn pull-right btn-success" type="button" data-dismiss="alert"> Aceptar</button></div>
HTML:
`
Este sitio web emplea cookies para ofrecerle un servicio más
 personalizado.
Si continúa navegando entenderemos que acepta nuestra
Políticas de tratamiento de la información de nuestro sitio web.
Aceptar
`
I am not sure what exactly is the alert you are talking about since it is not shown in your html.
The correct syntax of your script should be that:
$(".btn_cerrar").on('click', function(){
// Do what you want.
});
Now if the element you want hide can be selected from the selector $(".pb-element-alert") you mention in your question then you can use this:
$(".pb-element-alert").hide();
All of it together would be:
$(".btn_cerrar").on('click', function(){
$(".pb-element-alert").hide();
});
UPDATE
$( document ).ready(function() {
bool isBtnClicked = sessionStorage.getItem('buttonClicked') == true;
if(isBtnClicked){
$(".pb-element-alert").hide();
}
});
$(".btn_cerrar").on('click', function(){
sessionStorage.setItem('buttonClicked', true);
$(".pb-element-alert").hide();
});

Bootstrap dropdown and Jquery click function

I'm trying to make an action when someone click on a element of my dropdown.
I don't understand why, click function doesn't work.
My html code :
<div class="row">
<div class="dropdown col-lg-12">
<button class="btn btn-success dropdown-toggle" type="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="true">
Veuillez sélectionner la manière dont vous souhaitez nous contacter
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li>Etre rappelé</li>
<li>Envoyer un message</li>
</ul>
</div>
</div>
My Jquery code :
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
Never it goes in click function.
Thanks
It looks like your javascript code is getting executed before those elements exist,
I suggest you to try like this
$(function(){ // Wait until you have all html printed
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
});
Use JQuery version above 1.9.1
with following code
$(function(){ // Wait until you have all html printed
var phoneForm = $("#phoneForm");
console.log($("#callback"));
console.log($("#phoneForm").hasClass("hidden"));
$("#callback").click(function(){
console.log("entre dans la fonction click");
if(phoneForm.hasClass("hidden")){
console.log("entre dans le if");
phoneForm.removeClass("hidden");
}
});
});

how to add a caption to a jquery gallery

I'm using a hand made jquery gallery based on this tutorial : http://www.alsacreations.com/tuto/lire/719-galerie-images-simple-jquery.html
I've made a plugin of this gallery to use it several time in a same page.
From here, no real problem. My question is, how to add a text caption with this plugin. I've tried lots of things without finding a solution.
Here is the jquery gallery code :
jQuery(function($){
// définition du plugin
$.fn.ben_galerie = function(options) {
// définition des paramètres par défaut
var defaults = {
activeClass: "active",
activeTitle: "Photo en cours de visualisation",
loaderTitle: "Chargement en cours",
loaderImage: "/ben/images/loader.gif"
};
// mélange des paramètres fournis et des paramètres par défaut
var settings = $.extend(defaults, options);
function initGallery(ul)
{
var thumbLinks = $(this).find("a"), //référence toutes les vignettes cliquables dans un tableau
firstThumbLink = thumbLinks.eq(0), //et extrait le premier élément
//listeLinks = $(this).find("li"),
highlight = function(elt){
thumbLinks.removeClass(settings.activeClass).removeAttr("title"); //supression de l'attribut title
elt.addClass(settings.activeClass).attr("title",settings.activeTitle); //ajout du nouvel attribut title pour l'image en cours de visualisation
},
loader = $(document.createElement("img")).attr({ //chargement des parametres du loader
alt: settings.loaderTitle,
title: settings.loaderTitle,
src: settings.loaderImage
});
highlight(firstThumbLink);
var imgViewer = $(document.createElement("p")).attr("class","viewer") //creation d'un paragraphe qui fera office de récepteur pour les images grand format
.append(
$(document.createElement("img")).attr({ //extraire le contenu de l'attribut href de la première vignette photo
alt: "",
src: firstThumbLink.attr("href") //et le renseigner en tant que valeur de l'attribut src d'un nouvel objet image créé
})
);
$(this).after(imgViewer);
var bigPic = imgViewer.children("img");
thumbLinks //fonction qui sera déclenchée au clic sur chaque élément ciblé
.click(function(e){
e.preventDefault(); //annule l'événement par défaut lors du clic sur le lien
var $this = $(this), //$(this) = vignette cliquée et stocké dans $this pour ne pas parcourir pls fois le DOM
target = $this.attr("href");
if (bigPic.attr("src") == target) return;
highlight($this);
imgViewer.html(loader);
bigPic
.load(function(){
imgViewer.html($(this).fadeIn(250));
alert(caption);
})
.attr("src",target);
});
}
$(this).each(initGallery);
// interface fluide
return $(this);
};
// utilisation du plugin
$(document).ready(function() {
$(".thumbs").ben_galerie({
activeClass: "ssg_active",
activeTitle: "ben galerie : Photo en cours de visualisation",
loaderTitle: "ben galerie : Chargement en cours",
loaderImage: "images/loader.gif"
});
});
});
And here is a part of the html associated :
<div id="bloc_page">
<div id="contenu">
<div class="item">
<div class="galerie">
<div class="thumbs">
<div class="mini">
<li> <img alt="Description illus 1" src="images/galerie/illus/small/mini1.jpg" /></li>
<li> <img alt="Description illus 2" src="images/galerie/illus/small/mini2.jpg" /></li>
</div></div></div></div></div>
I'm thinking of using the title or the alt attribute, but I don't known how :/
Any tips or ideas will be fantastic.
Thanks guys !
you should use the alt attribute for the caption put it into a variable and call that variable in a caption element from you gallery. for example something like this
caption = $('img').attr("alt").text();
$('.whatever you call your caption element').text(caption);

Categories

Resources