Change window.location.href upon dismissal of modal - javascript

Following OctoberCMS guidelines I need to redirect users when they attempt to reach a certain path (ex: www.foo.com/bar) to the home page with php variables (ex: www.foo.com/?bar=1) and have a modal open if the variable is found.
I've created bar.htm which redirects with the proper variable:
title = "bar"
url = "/bar"
layout = "default"
meta_title = ""
meta_description = ""
is_hidden = 0
==
<?php
function onStart() {
header('Location:/?bar=1');
}
?>
==
and then in my JS (with #submitBtn being the button on the modal to send the form)
$(document).ready(function(){
if(window.location.href.indexOf('1') > -1) {
$('#myModal').modal('show');
$('#submitBtn').click(function() {
window.location.href='/';
})
}
});
So this is not working, it is just showing the modal in a constant loop and never moving to the success modal or changing the href. This form is working properly in all other situations, so I do not believe the issue lies there.
Shortened example modal code:
$('#myModal').on('show.bs.modal', function (event) {
var newForm = $('#newFakeForm');
var config = {
submitBtn: $('#submitBtn'),
contactModal: $('#myModal'),
successModal: $('#successModal'),
};
initContactForm(newFakeForm, config);
});
and my HTML button to dismiss the modal:
Thank you

What if you do the redirect on JS?
Just listen for the hidden.bs.modal event and do the redirect there.

Related

HTML Component That Is Fetched With JavaScript Not Responding To Click Event

I have an HTML component that is fetched when user clicks on a button. This component/modal is used to change a user's profile image (this is processed with PHP). The JavaScript fetch() happens with the following code:
var newProfileImageButton = document.getElementById('replace-profile-photo'),
changeProfileImageWrapper = document.getElementById('change-profile-image-wrapper'),
profileImageModalPath = "modals/change-profile-image.php";
newProfileImageButton.addEventListener('click', function(){
fetch(profileImageModalPath)
.then((response) => {
return response.text();
})
.then((component)=>{
changeProfileImageWrapper.innerHTML = component;
})
.catch((error => {console.log(error)}))
})
This fetched component includes a 'close' button should the user wish to close the modal and not update their profile image.
When I click the close button though nothing is happening. I have the script below - is the issue to do with the fact the Javascript has loaded before the component/modal is fetched? And if so how do I fix this? I guess I could just toggle display:none off and on for this component but would prefer to fetch it if possible.
Note: The button is responding to CSS hover events so I'm confident it's not an HTML / CSS markup issue.
// close button is part of the HTML component that is fetched
var closeComponent = document.getElementById('form-close-x')
if (closeComponent) {
closeComponent.addEventListener('click', function(){
// Hide the main component wrapper so component disappears
changeProfileImageWrapper.style.display = 'none';
})
}
I've also tried using the following code, which I found in a similar question, but this doesn't work either (it was suggested this was a duplicate question).
var closeComponent = document.getElementById('form-close-x')
if (closeComponent) {
closeComponent.addEventListener('click', function(e){
if (e.target.id == 'form-close-x') {
changeProfileImageWrapper.style.display = 'none';
}
})
}
Try this:
// var closeComponent = document.getElementById('form-close-x') <-- remove
// if (closeComponent) { <-- remove
document.addEventListener('click', function(e){
if (e.target.id === 'form-close-x') {
changeProfileImageWrapper.style.display = 'none';
}
})
//} <-- remove

jQuery Issue about Continue button opens external link in multiple browser tabs

I am doing one feature about showing alert on external link(apart from current domain) click. For that, I have written below code. All is working fine except below scenario.
$('a').each(function() {
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.click(function(event) {
//console.log($a.get(0));
//var myClasses = this.classList;
//console.log(myClasses.length + " " + myClasses['0']);
$("#redirectconfirm-modal").removeClass('hide');
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
$modal.on('show', function() {
$modal.find('.btn-continue').click(function() {
confirmed = true;
$a.get(0).click();
$modal.modal('hide');
location.reload();
});
});
$modal.on('hide', function() {
$a.get(0).removeClass("selected");
confirmed = false;
});
$modal.modal('show');
}
});
}
});
Scenario which produces this issue:
Click on any external link from the site, it open a modal popup for redirection confirmation with continue & return button.
If I click on "Return" button it closes the modal popup.
Now, I am clicking on external link from my site, it open the modal again but this time I am clicking on "Continue" button & guess what, it open that external link in 3 different tabs
Actually on each anchor tag click, it saves whole anchor tag value. I think, if remove all these anchor tag values on modal close code i.e. $modal.on('hide', function() { }) it will resolve problem. I had tried with many different ways but still facing this issue.
Can you please provide solution/suggestion on that?
Problem is when you have 3 external links (as you probably have), than you set 3 times this part of code:
$modal.on('show', function() { ... });
$modal.on('hide', function() { ... });
which is wrong. Those events listeners should be set only once.
Some simplified code would look like this:
var $modal = $("#redirectconfirm-modal");
var currentDomain = 'blabla';
$modal.on('click', '.btn-continue', function(e) {
window.location = $modal.data('redirectTo');
});
$('a').each(function() {
var $a = jQuery(this);
if( $a.get(0).hostname && getDomain($a.get(0).hostname)!=currentDomain ) {
$a.click(function(e) {
$modal.data('redirectTo', $a.attr('href'));
$modal.modal('show');
});
};
});
Don't inline your events, you may try something like this:
$('a').each(function() { //add a class to all external links
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.addClass('modalOpen');
}
});
$('.modalOpen').not(".selected").click(function(event) { //open the modal if you click on a external link
event.preventDefault();
$('.modalOpen').addClass('selected'); //add class selected to it
$modal.modal('show');
});
$modal.on('hide', function() {
$('.selected').removeClass("selected");//remove the class if you close the modal
});
$('.btn-continue').click(function() {
$('.selected').click();//if the users clicks on continue open the external link and hide the modal
$modal.modal('hide');
});

Show modal to user when updated

I have made this modal and it shows only on first visit to the website
$(document).ready(function(){
setTimeout(function(){
if(!Cookies.get('modalShown')) {
$("#myModal").modal('show');
Cookies.set('modalShown', true);
} else {
alert('You already saw the modal')
}
},1000);
});
In the modal it shows content of what new functionality to the application is added. So my target is to show the modal to the user every time I update the modal content. How can I do this?
You could use versionning in your cookies values :
var currentRelease = "1.0.1",
currCookie = Cookies.get('modalShown')
setTimeout(function(){
if(!currCookie || currCookie != currentRelease) {
$("#myModal").modal('show');
Cookies.set('modalShown', currentrelease);
} else {
alert('You already saw the modal')
}
},1000);
Note that this method forces you to update the value of "currentRelease"
you could also crypt the text content of the modal into md5 and use that value in your cookie, so whenever the modal value change, the md5 changes
So this is what worked for me:
$(document).ready(function() {
var currentRelease = document.getElementById("version").innerHTML;
var currCookie = Cookies.get('modalShown');
setTimeout(function () {
if(!currCookie || currCookie != currentRelease) {
$("#myModal").modal('show');
Cookies.set('modalShown', currentRelease);
}
}, 1000);
});
The id version is part of modal-content so as soon as I change something within the content the user will see the modal again on first visit since the change in the content.

Javascript change location href and click on a certain button

I would like to redirect the user onclick to a certain page "user/logged_in1" if the user is not already on that page and after the redirect a certain button must be clicked. This button opens a modal.
Doesn't work with this function:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
It seems it searched already for the button before the redirect happens and therefore the list is empty. How to fix this?
EDIT
This is a little bit more complex. The modal should only open if the user uses the redirect. If I use onload on the body tag, the modal will always open if the page is loaded, I don't need that. I need that modal only to be opened if the redirect happens.
The whole thing is a Python flask application:
{% if current_user.zahlung_iban == None and have_this_user_a_room != None %}
<li><a class="btn mybtn" onclick="redirect_to_logged_in_and_open_modal()" data-toggle="modal" data-target="#premium-special-modal"> Zimmer anbieten </a></li>
{% else %}
<li><a class="btn mybtn" href="{{ url_for('zimmer_einstellen') }}"> Zimmer anbieten </a></li>
{% endif %}
As you see there is a certain trigger for the button to become the redirect button.
EDIT
Okay working with a cookie sounds like a possible solution. But I cant figure out how to delete the cookie after the button was clicked, none of the proposed code works, eventhough it looks simple:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.cookie = "redirected_coz_of_click";
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
if (document.cookie.indexOf('redirected_coz_of_click') > -1 ) {
document.getElementsByClassName("zimmerbtn")[0].click();
delete_cookie('redirected_coz_of_click');
console.log(document.cookie);
} else {
console.log("cookie removed");
}
}
});
1: Append a parameter to the redirect url
user/logged_in1?click=btn_id
2: On landing on that page you can then check if the parameters is there. Found this method
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Found the method here: https://stackoverflow.com/a/21903119/3514785
So you could use it like this:
var btnToClickId = getUrlParameter("click");
3: With jquery (or javascript if you want) fire the click event on that btn:
$("#"+btnToClickId).click();
NB: You want to do the check after the page has loaded:
$(window).on("load",function() {
var btnToClickId = getUrlParameter("click")
if(btnToClickId) {
$("#"+btnToClickId).click();
}
});
So in summary
a: Edit your page and remove this line document.getElementsByClassName("zimmerbtn")[0].click(); because it is pointless
b: In the target page in the js copy and past the `getUrlParameter' method.
c: Then inside a on window load event listener do the url check as specified in 3.
ALTERNATIVE TO URL PARAMETER
You could instead use localStorage or some cookie to store the target id right before redirecting. Make sure you remember to clear it in the target page after grabbing it so that it is not always triggered even when you have not redirected from the page that triggers this whole process.
You can not access elements that have not even loaded yet.
By using location.href = '' you are simply directing a user to a page, any javascript after will fail because the page hasn't been loaded yet.
You tell us that you want to redirect a user to a page onclick. This sounds like the essential of an anchor tag:
Click Me
For step 2, just place the javascript on the page you are redirecting to. Bind to the load event of the page and then execute your javascript:
window.onload = function() {
document.getElementsByClassName("zimmerbtn")[0].click();
};
You can use cookie.
Set cookie when user click on the redirect button and when page is loaded, check if the cookie is set and open the modal. When you done with opening the modal clear the cookie. In that way you can easily achieve this.
Instead of triggering click. Call the onclick function in body onload method of user/logged_in1.
<body onload="openModal()">
You are trying to access a content on your initial page, but you have already redirected the user from that page, so this cannot be achieved by the current method.
I believe what you are trying to do is to open up a modal, after redirecting, do the following.
On your redirected page add the following, use jquery to achieve this
$( document ).ready(
// add the functionality to launch modal here
);
I created an onclick() function for this button:
onclick="redirect_to_logged_in_and_open_modal()"
In the function I check if I am not already on the logged_in site. If not I redirect but I add an additional parameter to the URL ?redirected.
In the next step if the logged_in is loaded and the parameter is in the URL the modal will also open, thats it.
Thanks #Zuks for the Idea adding a param to URL.
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
window.location.assign("https://www.example.com/user/logged_in1?redirected");
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
if(window.location.href.indexOf("redirected") > -1) {
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
});

Can I reset the validation for a Required Field Validator in a Javascript function?

-I have an aspx page that has several required field validators.
-After the user clicks on the save button and the page fails the validation you can no longer do anything on the page except fill in the fields.
-Three of the fields are disabled and are filled by clicking on a button that runs a javascript function that opens a popup where the user chooses a person and return the id of the person. The javascript function triggers a server side event that fills the fields.
The problem is that the trigger is never fired because the page is invalid.
Is there any way to reset the validation when the user clicks on the button?
-The javascript function does fire and open the popup but the trigger on the page that is failed will not work.
Things I have already tried:
do a postback in the javascript function - page does not post back
CausesValidation="false" - does not work
Page_BlockSubmit = false - no effect
Page_IsValid = true - no effect
The javascript function is as follows:
function OpenStudentPopup(pDistrictId) {
var modal = PopupContainer.createPopup('modal');
var pc = new PopupContainer(modal, {
src: '/pages/popup/SearchPerson.aspx?id=' + pDistrictId,
showConfirmationWhenClosing: true,
close: function (pData) {
$("#hdnChild").val(pData);
var sse = new ServerSideEvent('tgrChild');
sse.fire();
}
});
}
Finally found the answer.
In my Javascript function I added the following code:
Page_ValidationActive = false;
This allows the trigger to be fired and resets the entire page until a user tries to save again.
//New Javascript function
function OpenStudentPopup(pDistrictId) {
Page_ValidationActive = false; //This resets the validation
var modal = PopupContainer.createPopup('modal');
var pc = new PopupContainer(modal, {
src: '/pages/popup/SearchPerson.aspx?id=' + pDistrictId,
showConfirmationWhenClosing: true,
close: function (pData) {
//if (pData == true) {
$("#hdnChild").val(pData);
var sse = new ServerSideEvent('tgrChild');
sse.fire();
//}
}
});
}

Categories