Bootstrap dropdown change icon class on page reload - javascript

I'm using the Bootstrap framework dropdown as a sort of select. See image bellow:
When the user clicks on each of the dropdown links, a js function is fired to set a cookie defining the user's city/region. -> This is working!
The same function adds a class to the icon of the clicked link within the dropdown to indicate the selected item/city (see the "green dot icon" in the image above). -> This works as soon as the link is clicked!
BUT
The function fails to keep the icon new css class after the page reloads, and I have no active item at all, only two grey dots. -> Fail!
Here's the html:
<a href="#" id="city_1'" class="define-city-1" data-city="city1" role="menuitem">
<i class="icon large-point grey-300" aria-hidden="true"></i>
Betim
</a>
function reload_city() {
setTimeout(function() {
// redirect to the current url + the query string built with the cookie value
window.location = window.location.pathname + '?city=' + jQuery.cookie('city');
}, 1000);
}
jQuery("#city_1").click(function(e){
e.preventDefault();
jQuery.cookie('city', jQuery(this).attr('data-city'));
if(jQuery(this).attr('data-city') == jQuery.cookie('city')){
jQuery(this).children('i').removeClass('grey-300');
jQuery(this).children('i').addClass('green-600');
}
reload_city();
e.stopPropagation();
});
I was wondering what causes this behavior on reload, and I'd really appreciate any inputs regarding this issue. Thanks in advance!

Related

Pass on HTML element attribute to another element attribute

I’m using Elementor Pro for website development. I created a standard popup that is triggered if the user clicks on a link on the page like this
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink1.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink2.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink3.com”>test link</a>
<a href="#elementor-action-foo” data-extlinkurl="https://www.mylink4.com”>test link</a>
The popup (on the same page) has a button that will forward the user to the external link previously clicked:
Take me to the link
Elementor offers no option to dynamically set the href value of the button based on the custom attribute (in this case “ext-link”), but I found no other option to dynamically set the href attribute of this button. Is there an easy JavaScript /jQuery escape here (no plugin!) that can be used to pass on the custom attribute value to the button link attribute?
EDIT -
I did some tryouts to fund a solution for this problem and I came up with the following:
<script>
// Append an onclick event to each link
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
The onclick event is added properly to each link here.
Because the function setLink (see below) did not work, I added some checks here:
console.log("Button count=" + document.querySelectorAll('#extlinkbtn').length); // Button count=1
console.log("Button href=" + document.getElementById("extlinkbtn").href); // Button href=http://www.test.com/
console.log("Button href=" + document.getElementById("extlinkbtn").getAttribute("href")); // Button href=http://www.test.com
These provided the expected results. The button is found and the href attribute is available.
function getUrl() {
var newUrl = event.currentTarget.getAttribute('data-extlinkurl');
console.log("newUrl=" + newUrl); // newUrl=https://www.mylink1.com
setUrl(newUrl);
}
Also works properly. When the link is clicked, the data attribute of the link is available.
function setUrl(newLink) {
let linkButtons = document.querySelectorAll('#extlinkbtn');
console.log("count=" + linkButtons.length) // count=0
linkButtons.forEach((linkButton) => {
linkButton.setAttribute("href", "'" + newLinkUrl + "'");
});
}
</script>
Here it becomes problematic. Once the link is clicked, the button cannot be found. The button is there, because the popup with the button is displayed on screen and the element visible. I'm testing several days now and either solution I tried did not work. Why is the button element found if searched on a global scope, but after the link is clicked the button is not available in the function scope?
Eventually and not thanks to the Elementor second line support, I found a solution. It seems that the content of the popup was initially loaded but deleted by a function after the DOM was loaded.
The solution was here: https://developers.elementor.com/elementor-pro-2-7-popup-events/
What I did was adding a custom data attribute to the link button that is clicked in the popup screen after this is loaded which holds the target URL. After this, I added some JS/jQuery to the popup template:
<script>
let newLinkUrl = "";
let extLinkItems = document.querySelectorAll('[data-extlinkurl]');
extLinkItems.forEach((extLinkItem) => {
extLinkItem.setAttribute("onclick", "getUrl()");
});
function getUrl() {
newLinkUrl = event.currentTarget.getAttribute('data-extlinkurl');
jQuery( document ).on( 'elementor/popup/show', () => {
document.getElementById('extlinkbtn').href=newLinkUrl;
});
}
</script>
This works perfectly

X-Editable AJAX call not working after disabling / enabling

I recently stumbled across a problem with enabling / disabling X-Editable forms which I have (after days of trying) not been able to solve yet. Any help would be greatly appreciated.
I've created a fiddle containing the core of my problem:
http://jsfiddle.net/xBB5x/11749/
I have multiple labels which are editable;
The input should be submitted to a server using ajax;
Up to here everything works perfect. But then there is also a button who is basically just disabling and enabling (right after disabling) the x-editable functionality.
If you click this button before you edit the labels - the AJAX call isn't made.
Things you might find suspicious:
The selector: In my (simplified) example, the selector isn't actually needed. It's there because parts of our application are dynamically (re)loaded.
Why am i trying to do this? I have multiple labels which should all be editable - but only one at I time. So if the focus changes, I disable all of them and enable the one who just got the focus. Well, at least I try to do that...
Thanks for any help!
Here's the HTML:
<button type="button" id='thebutton'>Don't click Me!</button>
<div style="margin: 150px" id='navi'>
<h4>
<a href="#" class='title'>awesome 1</a>
</h4>
<h4>
<a href="#" class='title'>awesome 2</a>
</h4>
<h4>
<a href="#" class='title'>awesome 3</a>
</h4>
</div>
<div id='output'>
...
</div>
And here's the JS:
$('#navi').editable({
selector:'.title',
url: function(params) {
$.ajax({
url: '/echo/js/?js=SUBMITTED!',
complete: function(response) {
$('#output').html(response.responseText);
},
error: function() {
$('#output').html('Bummer: there was an error!');
},
});
},
send: 'always'
});
jQuery('body').on('click', '#thebutton', function () {
$('.title').editable('toggleDisabled');
$('.title').editable('toggleDisabled');
})
Edited - Some additional information:
We have a navigation (which is basically a "folder structure") which is created by the user. This means the user should be able to add additional navigation items and rename them if he wants. The user is only allowed to rename the active item. The content of each item gets dynamically loaded in the main panel.
The Navigation
So when the user selects an item, the following script is run (which disables x-editable functionality on all links and reactivites it on the new active one:
if (!$(this).hasClass("active")) {
// Load content to the main panel
DisplayOpRiskLeaf($(this).attr('id'));
// Change active navigation element
$('.oprisk-link').removeClass("active");
$(this).addClass("active");
$('.oprisk-leaves-panel').removeClass("active");
$(this).parents('.oprisk-leaves-panel').addClass("active");
// Change x-editable...
// disable all ($(this) is also getting disabled here)
$('.portfolio-title').editable('option', 'disabled', true);
// enable the active elemnt
$(this).editable('option', 'disabled', false);
}

Enable link after first click

Requirements:
When I clicked first time on menu item which has dropdown menu, It should show its dropdown and when I clicked on the same menu item second time it will redirect to its own page.
Please consider the situation. Menu item redirect to its own page only when its dropdown are opens
Reference Images:
Reference website link:
Reference website link
Note for referaence website:
1) Please open reference website link on mobile view.
2) Click on about page than Dental Page and than again About page , When you second time clicked on about page It goes to its own page. But on this occasion I want to open its dropdown and again If I clicked About page than it goes to its own page
Currently I am using jQuery bind function and disable link through event.preventDefault() but i didn't resolve my problem
Here's my code
jQuery Code:
$(document).ready(function(){
$(".flexnav li.parent-menu-item > a").bind("click.myclick", function(event) {
event.preventDefault();
$(".flexnav li .sub-menu").hide();
$(this).unbind(".myclick");
$(this).parents(".flexnav li.parent-menu-item").children(".sub-menu").toggle();
});
});
Sorry for my language mistakesThanks!
Instead of handling the click event inside the $(document).ready function, you should try doing it inline with each li.
<li id="link1" onclick="ShowMenu('#menu1', 'index.html')">
<ul class="dropdown" id="menu1">
...
</ul>
</li>
<li id="link2" onclick="ShowMenu('#menu2', 'aboutus.html')">
<ul class="dropdown" id="menu2">
...
</ul>
</li>
<script>
function ShowMenu(menuId, linkRef){
var display = $(menuID).css('display');
if(display == 'block')
window.location.href = linkRef;
else{
$('dropdwon').hide();
$(menuId).show();
}
}
</script>
So, here, what I am doing is to call the ShowMenu() function with the id of the menu I want to show, as the parameter and the url of the page linked to it.
The function then checks if that menu is being displayed or not. If being displayed then it redirects the user to the url. If not, then it proceeds to hide all other dropdowns and shows only the one that was clicked.
You can use CSS class toggle to see if the dropdown is open or not and perform the action accordingly. (Assuming your current code is working fine to open dropdown)
$("body").on("click",".flexnav li.parent-menu-item > a",function(e){
var dropdowns=$(this).parent('li').children(".sub-menu");
var menu=$(this).parents(".flexnav li.parent-menu-item").children(".sub-menu");
if(dropdowns.size()>0) {
if(!menu.hasClass('open')) {
e.preventDefault();
menu.addClass('open');
menu.show();
}
}
});

How do I close a Modal window and automatically navigate to Anchor using the same link?

I'm using Bootstrap 3.0 and I have an open Modal window with two 'buttons' at the bottom, one says 'Contact Us' and the other says 'Close'.
When someone clicks the 'Contact Us' button I want the Modal window to close and the user to be automatically taken to a specific anchor on the same page.
The following doesn't work. It does scroll the page to the desired anchor, but the user can't see this because it doesn't close the modal window...
<a class="btn btn-info" data-dismiss="modal" href="#section-contact">Contact Us</a>
Have you tried or thought about a jquery onclick function on the close button?
Maybe you can force the modal to close manualy with (see docs)
$('#myModal').modal('hide');
and navigate to the anchor using (see answer)
$(document.body).scrollTop($('#anchorId').offset().top);
and the result will be:
HTML:
<a class="btn btn-info" href="#" id="contact_btn">Contact Us</a>
jquery:
$('#contact_btn').click(function(){
$('#myModal').modal('hide');
$(document.body).scrollTop($('#anchorId').offset().top);
});
I have experienced the same issue, but the answer provided by Lan did not work for me.
Finally, I work it out by using onClick to close modal class .modal instead of using the id of the particular modal #myModal I wanted to close. This works because you can only have one modal open at a time in your web:
Contact us
Js
// .my-anchor = the class of the trigger
$('.my-anchor').on('click', function(e) {
e.preventDefault();
// it will search throughout .my-anchor ancestors to find the closest .modal
$(this).closest('.modal').modal('hide');
var hash = this.hash;
$('html, body').animate({ scrollTop: $(hash).offset().top }, 300);
});
HTML
// clicking this link will close the modal and scroll to wherever #products is located on the page
Click Here
In this example, hash will be #products, but it will update to any other anchor you might have
I am using for this issue another solution. I had the same problem while I have a modal with an "section" overview and i want to jump out of this modal on the same page to a specific section. I simply pass the section id in the link and pick the section ID by GET and do a PHP header to the section.
My HTML link in the modal:
<a class="small text-primary stretched-link" href="1.php?section_id=123"></a>
My PHP code on the same page (somewhere in header):
if($_GET){
$section_id = $_GET['section_id'];
header("Location: 1.php#$section_id");
}
if(!$_GET){
// Nichts wurde übergeben
}
None of the other answers worked for me. but this code did:
<a href="#contact" onclick='$(".modal").parent().hide()'>contact form</a>

Using javascript to close a foundation 4 dropdown button menu window

I am struggling with a JavaScript / jQuery issue. I am developing with foundation 4. I have a group of 5 buttons. Two of the buttons are dropdown buttons. When the dropdown button is pressed a window is presented with the dropdown options(links).
<a id="products" href="#" data-dropdown="prod" class="not_active_button_dropdown">Dropdown Button</a><br>
<ul id="prod" class="f-dropdown">
<li><a class="prod" href="index.php?info=basic">Basic</a></li>
<li><a class="prod" href="index.php?info=unifrost">Unifrost</a></li>
<li><a class="prod" href="index.php?info=teal">Teal-Sorb</a></li>
</ul>
Note: I created my own buttons classes with sass by mixin (class="not_active_button_dropdown").
Now I developed a script that loads the php response into a div #dropdownwrap, changes the buttons so it highlights the current button that has been pressed.
<script style="text/javascript">
$(document).on('click','a.not_active_button, a.prod', function(){
var href=$(this).attr('href');
var querystring=href.slice(href.indexOf('?')+1);
//get
$.get('index_jq.php', querystring, processResponse).error(errorResponse);
//reset all buttons to not active
//normal button
$('a.active_button').removeClass("active_button").addClass("not_active_button");
//dropdown button
$('a.active_button_dropdown').removeClass("active_button_dropdown").addClass("not_active_button_dropdown");
//if it is a normal button make it active
if ($(this).hasClass("not_active_button"))
{
$(this).addClass("active_button");
}
//if it is a dropdown button option link make it active
if ($(this).hasClass("prod"))
{
$('#products').removeClass("not_active_button_dropdown").addClass("active_button_dropdown");
//$('ul#prod.f-dropdown').close();
}
//slide down wrap
if ($('.dropdownwrap').is(":hidden")) {
$('.dropdownwrap').slideDown();
} else {
$('.dropdownwrap').slideToggle("slow");
$('.dropdownwrap').slideDown("slow");
}
return false; // stop the link
});
function processResponse(data) {
$('.dropdownwrap').html(data);
}
function errorResponse() {
var errorMsg = "Your request could not be processed right now.";
errorMsg += "Please try again.";
$('.dropdownwrap').html(errorMsg);
}
</script>
I am not that experienced with JavaScript or jQuery. Anyhow the problem is the following:
//$('ul#prod.f-dropdown').close();
which is commented out above. Everything works fine, my data loads and the dropdown button highlights. The problem is that the foundation 4 dropdown button window does not close after the script executes. This is because (I am guessing) I return false to stop the link from executing. So I tried to close the window using the above commented out line. When I uncomment the line, the window closes but the return false does not execute, that is the link is not disabled, it goes to the link, i. e. index.php?info=basic. So it seems when I add the close window statement, return false does not work. I tried adding the line after return false, but it does not close the dropdown menu.
The return false; not working is probably because there is some JavaScript error before it reaches that line. In this case, the error is calling .close() on something which does not have a close method. Instead, in order to call Foundation dropdown’s close method, you have to do something like the following:
$('#prod').foundation('dropdown', 'close', $('#prod'))
I guess there is a more elegant way to do this, but I found this to work. As a note, next time please post a minimal example on jsfiddle.net and link to it in your question. This makes reproducing your problem much easier.
You also need the data-dropdown-content attribute attached to the dropdown ul element.
Reference: https://github.com/zurb/foundation/issues/1831#issuecomment-15133817

Categories