Display the selected/active link in a div using jQuery - javascript

I have a simple html menu, when a menu item is clicked a class of `mg_cats_selected" is added to the anchor tag (which is the menu item).
I would like to copy the text value of the active/selected anchor tag and display it in another div on the page, but I would like to only display it once. When a new item link is clicked, I want to remove the old value from the separate div that I've created it and display the new value of the new selected menu item.
I hope that makes sense.
This is the HTML menu
<div id="mgf_165" class="mg_filter mg_new_filters">
<a rel="163" id="163" class="mgf_id_163 mgf mg_cats_selected left_menu" href="javascript:void(0)">Bathrooms Sinks</a>
<a id="164" rel="164" class="mgf_id_164 mgf left_menu" href="javascript:void(0)">Bowed</a>
</div>
This is the jQuery and the div where I wanna display the text values.
<script type="text/javascript">
jQuery(document).ready(function(){
console.log('test');
jQuery("a.left_menu").click(function(){
var txt = jQuery("a.left_menu").text();
//$(this).attr('rel');
jQuery("#category").append(txt);
});
});
</script>
<div id="category">
</div>
At the moment when I click on, say, "Bowed", this displays in the div
Bathrooms SinksBowed
And if I click again on "Bathroom Sinks", the same thing repeats
Bathrooms SinksBowedBathrooms SinksBowed
How can I deal with that? And did I follow the correct logic here?

You are currently getting the text of all the menu items and then appending it to the div.
You need to get the text of the clicked menu item, and then set the content of the div to the text value of that menu item.
jQuery(this) // the clicked menu item
jQuery('#category').text('VALUE') // set the text content of the tag to VALUE
Working solution on JSFiddle..
See Inside the Event Handling Function to learn more about jQuery event handling.

Related

How to make custom dropdown menus

Im realtively new to html/css and having trouble finding a way to make an element that I want. Ill start off with saying that I am using Material Design Lite in a rails project.
So what Im trying to do is I have a grid of search results and Im trying to create a filter bar that users can select different tags and characteristics to filter the results. The html and form part to filter the results I can handle the part that Im having trouble figuring out is the way I want the layout...
Im trying to create a bar across the top with different categories and when the user clicks on one of the categories a box expands with all the different filtering options for that category. Similar to a menu dropdown but looking to make it part of the group so if they choose another category it will close the first one and open the new one instead.
Im looking for a push in the right direction to find a tutorial or example that will get me in the right direction. For a visual reference for what Im thinking the recipe website yummly uses this kind of system...heres a screen shot:
Using jQuery, you can add an attribute for your top navigation's links corresponding to an ID on each individual group, then use that to target the correct tab, and fade out the rest with .siblings()
HTML
<div id="topbar">
link
link
</div>
<div id="groups">
<div class="sub" id="category1">
filter
filter
filter
filter
filter
</div>
<div class="sub" id="category2">
filter
filter
filter
filter
filter
</div>
</div>
jQuery
$(document).ready(function(){
$(".sub, .close").hide(); // hides filter tabs and close button
$('#topbar a.toggle').click(function(){ // on click
var category = $(this).attr("data-group"); // checks the ID to fade in
$(".sub" + category).fadeIn().siblings(".sub").hide(); // fades in the correct subcategory and fades out all the other categories
$(".close").fadeIn(); // fades in close button
return false; // prevents anchor link behaviour
});
$("#topbar a.close").click(function(){ // close button click
$(".sub").fadeOut(); // fades out whatever subcategory is active
$(this).fadeOut(); // fades out close button
return false; // prevents anchor link behaviour
});
});
jsFiddle: https://jsfiddle.net/4t6k2ftd/
You can do this with tabs. There are lot of tutorials for this. In your case ingredients, taste, diet(links) can be tabs. For each tab you have tab-content.For example "Diet filter options"(content) for "diet tab"(tab). When you click on "diet tab" "diet filter options"(content) is made visible and some css is added. Here is a tutorial.
Example tabs html
<ul class='tabs'>
<li><a href='#ingredients'>Ingredients</a></li>
<li><a href='#tastes'>Tastes</a></li>
<li><a href='#diet'>Diet</a></li>
</ul>
<div id='ingredients'>
Ingredients filter options
</div>
<div id='tastes'>
tastes filter options
</div>
<div id='diet'>
diet filter options
</div>
Example tabs javascript(jquery)
$('ul.tabs').each(function(){
// For each set of tabs, we want to keep track of
// which tab is active and its associated content
var $active, $content, $links = $(this).find('a');
// If the location.hash matches one of the links, use that as the active tab.
// If no match is found, use the first link as the initial active tab.
$active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
$active.addClass('active');
$content = $($active[0].hash);
// Hide the remaining content
$links.not($active).each(function () {
$(this.hash).hide();
});
// Bind the click event handler
$(this).on('click', 'a', function(e){
// Make the old tab inactive.
$active.removeClass('active');
$content.hide();
// Update the variables with the new link and content
$active = $(this);
$content = $(this.hash);
// Make the tab active.
$active.addClass('active');
$content.show();
// Prevent the anchor's default click action
e.preventDefault();
});
});
Here active is class for currently active link.

Jquery Mobile Column Toggle append button when have multiple tables on one page

I have an issue with a jquery mobile 1.4.2 webapp. I have a page with 2 tables that both use the column toggle button. I want to move each of these buttons to their own placeholder to allow for horizontal scrolling.
I have this working when there is one table, but I can't figure out how to specify the table id for the column toggle button, to move the button for the correct table.
<div id="colUnit"></div>
$(document).on("pageinit", "#contractDetails", function () {
$(".ui-table-columntoggle-btn").appendTo("#colUnit");
});
Is there a way to specify the table id within the jquery so that the correct button is moved to <div id="colUnit"></div>
It currently places BOTH buttons (one from each table), into <div id="colUnit"></div>
column-toggle buttons are siblings of tables and placed before them. Use .prev() to move to another place.
$("#mytable1, #mytable2")
.prev(".ui-table-columntoggle-btn")
.appendTo("#colUnit");
Update
You can also append them into a controlgroup and change their text.
<div id="colUnit" data-role="controlgroup" data-type="horizontal"></div>
Move buttons to controlgroup.
$("#mytable1, #mytable2")
.prev(".ui-table-columntoggle-btn")
.each(function () {
var text = $.mobile.path.parseUrl($(this)
.prop("href"))
.hash.substring(1);
$(this)
.text(text.split("-")[0])
.appendTo($("#colUnit")
.controlgroup("container"));
});
$("#colUnit").controlgroup("refresh");
Demo

get Attribute of Hovered element that displayed menu

I have a menu that is displayed when a user hovers over an anchor tag with a certain class. The same menu is always displayed, but the anchor tags have a different "accNum" attribute. I want to get the value of the accNum attribute from the "parent" element that displayed the menu and append it to the click event of one of the menu items. Something like;
Actions
Actions
Actions
<div id="ActionsMenu" style="display:none;">
Show Account
</div>
Whichever 'ActionLink' is the one hovered over to display the menu, i want to take that AccNum value and create the onClick event of "ShowAccountValues" something like
onClick="showAccountValues('AccNum value of parent');"
any help would be great. Also, I assume I have to bind this to the document.ready() function for 'ActionLink' which makes sense, but i figured if i could get any of it through this that would be great.
Thank you
Firstly use jQuery to hook up your events, secondly accnum isn't a valid attribute, so use a data-* attribute like this:
Actions
Actions
Actions
<div id="ActionsMenu" style="display:none;">
Show Account
</div>
Then you can update the data attribute of the #showAccountValues link on hover of each a element:
$('.actionLink').on({
click: function(e) {
e.preventDefault();
$('#ActionsMenu').show();
},
mouseover: function() {
$('#showAccountValues').data('accnum', $(this).data('accnum'));
}
});
Then on the click of the a element in #ActionsMenu you can get the accnum:
$('#showAccountValues').click(function(e) {
e.preventDefault();
showAccountValues($(this).data('accnum'));
});
Example fiddle

JavaScript: Toggle between 3 elements, only one is active

I just started with JavaScript and have a small question. On my website I have three div-elements:
<div id="id_1" class="class_1" onclick="itemSelected('id_1')"></div>
<div id="id_2" class="class_2" onclick="itemSelected('id_2')"></div>
<div id="id_3" class="class_3" onclick="itemSelected('id_3')"></div>
I added the following script to highlight the one that the user has clicked:
var selected = false;
function itemSelected(element) {
if (selected == false) {
document.getElementById(element).style.backgroundColor = "#f5b03d";
selected = true;
}
else {
document.getElementById(element).style.backgroundColor = "#99d4e5";
selected = false;
}
}
So far, this works and the user clicks an item and it gets highlighted in another color. If he clicks it again, it gets his default background color. But as soon as the user clicks one of the other items, it gets highlighted too. What I want is a single-choice functionality: As soon as the user clicks one item, the other too appear in their default background-color. Can someone help me with this problem?
Thanks in advance!
Add a shared class to each element.
When the user clicks an element use that shared class to set the default background color to all three elements.
Then use the element's unique ID to set the highlighted background color to the element that has been clicked.
<div id="id_1" class="class_0" onclick="itemSelected('id_1')"></div>
<div id="id_2" class="class_0" onclick="itemSelected('id_2')"></div>
<div id="id_3" class="class_0" onclick="itemSelected('id_3')"></div>
function itemSelected(element) {
$('div.class_0').css({'background-color':'#99d4e5'});
document.getElementById(element).style.backgroundColor = "#f5b03d";
}
Change the html as above and use this jquery
You can do this without using javascript, created a fiddle for this:
http://jsfiddle.net/6PUwz/
What I have done is, making the divs focusable by setting tabindex="-1" and doing the selection by the use of the css-pseudo-class :focused.
Check if this fits you requirements.

set Tweet button 'data-text' contents dynamically with javascript, or..?

Here is functioning code on a form that displays a Tweet button -- the button's on a form that displays several images -- when the user clicks one of the images, it becomes the 'selected' image and the Tweet button is supposed to tweet the selected image's name and url:
<a id="tweetBtnId" href="https://twitter.com/share" class="twitter-share-button"
data-text="Check me out on OurWebSite!"
data-url=http://$ourSiteURL
data-via=http://$ourSiteURL data-size="medium" data-count="none">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
js.src="//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}
(document,"script", "twitter-wjs");</script>
I have an 'onclick()' handler for the div that displays the image. When the user clicks one of the images, its div's onclick() handler is called and sets that image to be the 'currentlySelectedImage' on the page -- and the onclick() handler then needs to update the Tweet button's 'data-text' attribute with the name of the just-selected image:
// This is part of the code of the 'onclick()' handler for
// the image being selected.
<script>
function handleImageOnClick()
{
var myDynamicTweetText = "name of currently-selected image goes here";
var elem = document.getElementById("tweetBtnId");
alert("The elem is: " + elem); // elem IS NULL !! Dagnabbit.
// this fails because 'elem' is null
elem.setAttribute("data-text", myDynamicTweetText);
// other onclick() code not shown for brevity......
}
</script>
I need to dynamically change the 'data-text' attribute's value in the Tweet button to be the name of the selected image. I added the javascript code above which fails-- the 'elem' obtained from the code here:
var elem = document.getElementById("tweetBtnId");
is null (I think) because of this line in the Twitter tweet button code above:
if(!d.getElementById(id)){js=d.createElement(s); js.id=id;
I'm not sure but it looks like the Twitter Tweet button default script overwrites any attempt
to add an 'id' attribute to the Tweet button.
You will see that I added the id="tweetBtnId" to the Tweet button above so I could get access to the Tweet button in my image-selection onclick() handler above, then set the 'data-text' to the name of the just-selected image.
I just doubt that Twitter's design goal for the Tweet button was "we're gonna dumb this sucker WAY down, we'll only let these animals choose ONE data-text value - every Tweet button has to have one hard-coded, "Once-on-the-page" data-text attribute - joke's on them if they try to dynamically change the Tweet button's data-text attribute."
I need to get this to work -- any ideas?
Just put it in a container with a known ID and traverse the document with it:
<div id="someIDiKnow">
<a id="tweetBtnId"...>...</a>
</div>
$("#someIDiKnow a").attr("data-text", "Replacement Text!");
Looks like it's going to be the kludgy hidden form/php variable approach for now -- I'll post back if I find a better work-around.
EDIT: the hidden-form/PHP variable solution has beaten the roadblock put up by Twitter's Tweet button -- I can now successfully, dynamically change the Tweet button text at will, anytime based on the user's client-side input. Per Domenic's astute observation that the question above is too long and has code in it, I'll skip posting the answer here, and I apologize for the length above.
You could use JQuery to update the attribute data-text by adding an onclick action on the image. If you wanted to include the text inside the actual image tag by adding your own attribute to the tag, that could be an easy work around to assembling the tweet text.
For example:
function updateTweetBtn(obj) {
$('#someIDiKnow a').attr('data-text', $(this).attr('tweet'));
}
<img src="/images/myimage.jpg" tweet="This is what I want to tweet" onclick="updateTweetBtn(this);" />
<img src="/images/myimage2.jpg" tweet="This is some other text I want to tweet" onclick="updateTweetBtn(this);" />
using in html
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
Tweet
I managed to change the 'data-text' with javascript
var a = "new text";
document.getElementsByClassName('twitter-share-button')[0].setAttribute("data-text", a);
also worked with document.getElementById('twitter') if you add id='twitter' to <a>

Categories

Resources