How to get title attribute from link within a class with javascript - javascript

I am trying to pull the title attribute from links within a class and having a bit of trouble:
<div class="menu">
United States
Canada
</div>
And here's what I've tried:
function cselect(){
var countryID = $(this).attr("title");
location.href = location.href.split("#")[0] + "#" +countryID;
location.reload();
}
Thanks!

Pass in this to your inline handler:
function cselect(obj){
var countryID = $(obj).attr("title");
console.log(countryID);
}
United States
Canada
Demo: http://jsfiddle.net/yDW3T/

You must refer to the clicked element. One way is to pass this, as tymeJV suggested.
But I would set the event handler from a separate script block and just refer to the current element. For both of the following two solutions no additional inline onclick attribute is required.
/* using jQuery */
jQuery( '.menu a' ).on( 'click', function( event ) {
event.preventDefault();
var countryID = jQuery( this ).attr( 'title' ); // <-- !!!
location.href = location.href.split( '#' )[0] + '#' + countryID;
location.reload();
} );
or
/* using plain JS */
var countryAnchors = document.querySelectorAll( '.menu a' );
for( var anchor in countryAnchors ) {
anchor.addEventListener( 'click', function( event ) {
event.preventDefault();
var countryID = this.getAttribute( 'title' ); // <-- !!!
location.href = location.href.split( '#' )[0] + '#' + countryID;
location.reload();
}, false );
}
/* todo: cross-browser test for compatibility on querySelectorAll() and addEventListener() */

It just simple like this:
function cselect(){
var countryID = $(this).attr("title");
window.location.hash = countryID
location.reload();
}

Related

javascript additional text change, on button click in jQuery isotope, other than filter function

I have following - jquery Isotope based filter implemented in my code, its filtering n displaying - filtered content, based on BUTTON click:
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match( /filter=([^&]+)/i );
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent( hashFilter );
}
$( function() {
var $container = $('.isotope');
// bind filter button click
var $filterButtonGroup = $('.filter-button-group');
$filterButtonGroup.on( 'click', 'button', function() {
var filterAttr = $( this ).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent( filterAttr );
});
// bind filter on select change
$('.filters-select').on( 'change', function() {
// get filter value from option value
var filterValue = this.value;
// use filterFn if matches value
filterValue = filterFns[ filterValue ] || filterValue;
$container.isotope({ filter: filterValue });
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if ( !hashFilter && isIsotopeInit ) {
return;
}
isIsotopeInit = true;
// filter isotope
$container.isotope({
itemSelector: '.offer-type',
layoutMode: 'fitRows',
// use filterFns
filter: filterFns[ hashFilter ] || hashFilter
});
// set selected class on button
if ( hashFilter ) {
$filterButtonGroup.find('.is-checked').removeClass('is-checked');
$filterButtonGroup.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on( 'hashchange', onHashchange );
// trigger event handler to init Isotope
onHashchange();
});
//# sourceURL=pen.js
</script>
Button code:
<div id="filters" class="button-group filter-button-group">
<div class="my123">
<ul>
<li>
<button class="button" data-filter=".a1">Red Apples</button>
</li>
<li>
<button class="button" data-filter=".b1">Green Apples</button>
</li>
</ul>
</div>
</div>
I am trying to change display value of following code, based on same button click. Means additional function, other than filteration.
<blockquote>
<p>
Value to be changed on each button click
</p>
</blockquote>
Tried so many things , but nothing worked. Help please.
var $filterButtonGroup = $('.filter-button-group');
$filterButtonGroup.on( 'click', 'button', function() {
var filterAttr = $( this ).attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent( filterAttr );
$("blockquote p").html("The value of data attr on button is" + filterAttr);
});
PS : You should definately use an id or class name for your blockquote's paragraph and also if you are using data attribute you can directly access it without attribute i.e
$(this).attr('data-filter');
works same as
$(this).data('filter')

JQuery plugin not working when used in multiple places in a single page

I am writing a JQuery plugin for a project I'm working on which turns from tabbed content on desktop devices to an accordion on mobile devices. I've used JQuery Boilerplate (https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/dist/jquery.boilerplate.js) as an initial pattern for my plugin.
The plugin is called on any element with the class ".tabs2accordion" as shown here:
$(".tabs2accordion").tabs2Accordion({state:"desktop"});
The plugin works as expected if there is only one element with ".tabs2accordion" class on a page but starts to malfunction as soon as another element with the same class is added to the page. I've created a codepen of the basic code to demo the issue. To show the issue, on a window size of >768px try clicking any of the titles and observe how the content below changes as each title is clicked. Next uncomment the block of HTML and try clicking on the titles again.
http://codepen.io/decodedcreative/pen/MyjpRj
I have tried looping through each element with the class "tabs2accordion" like this:
$(".tabs2accordion").each(function(){
$(this).tabs2Accordion({state:"desktop"});
});
But this didn't fix the issue either.
Any ideas?
I have not used jQuery Boilerplate, but I believe the problem here is with your variable called plugin.
Nowhere in your code do you declare a variable called plugin. When I stop the debugger in Plugin.prototype.showTabContent, I can evaluate window.plugin and it returns the global value for plugin.
In the constructor for Plugin, the first line reads plugin= this;. Since plugin is not defined, it is declaring the variable at global scope on the window object.
The fix is to pass a reference to the plugin object when setting up the $().on() hook. The data passed is available in the event handlers via the event parameter that is passed in the data property.
Here is the solution (at http://codepen.io/shhQuiet/pen/JXEjMV)
(function($, window, document, undefined) {
var pluginName = "tabs2Accordion",
defaults = {
menuSelector: ".tabs2accordion-menu",
tabContentSelector: ".tabs2accordion-content"
};
function Plugin(element, options) {
this.element = element;
this.$element = $(this.element);
this.options = $.extend({}, defaults, options);
this.$menu = $(this.element).find(this.options.menuSelector),
this.$tabs = $(this.element).find(this.options.tabContentSelector),
this.$accordionTriggers = $(this.element).find(this.$tabs).find("h3");
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
//Set all the tab states to inactive
this.$tabs.attr("data-active", false);
//Set the first tab to active
this.$tabs.first().attr("data-active", true);
//If you click on a tab, show the corresponding content
this.$menu.on("click", "li", this, this.showTabContent);
//Set the dimensions (height) of the plugin
this.resizeTabs2Accordion({
data: this
});
//If the browser resizes, adjust the dimensions (height) of the plugin
$(window).on("resize", this, this.resizeTabs2Accordion);
//Add a loaded class to the plugin which will fade in the plugin's content
this.$element.addClass("loaded");
console.log(this.$element);
},
resizeTabs2Accordion: function(event) {
var contentHeight;
var plugin = event.data;
if (!plugin.$element.is("[data-nested-menu]")) {
contentHeight = plugin.$tabs.filter("[data-active='true']").outerHeight() + plugin.$menu.outerHeight();
} else {
contentHeight = plugin.$tabs.filter("[data-active='true']").outerHeight();
}
plugin.$element.outerHeight(contentHeight);
},
showTabContent: function(event) {
var $target;
var plugin = event.data;
plugin.$menu.children().find("a").filter("[data-active='true']").attr("data-active", false);
plugin.$tabs.filter("[data-active='true']").attr("data-active", false);
$target = $($(this).children("a").attr("href"));
$(this).children("a").attr("data-active", true);
$target.attr("data-active", true);
plugin.resizeTabs2Accordion({data: plugin});
return false;
},
showAccordionContent: function(event) {
var plugin = event.data;
$("[data-active-mobile]").not($(this).parent()).attr("data-active-mobile", false);
if ($(this).parent().attr("data-active-mobile") === "false") {
$(this).parent().attr("data-active-mobile", true);
} else {
$(this).parent().attr("data-active-mobile", false);
}
}
};
$.fn[pluginName] = function(options) {
return this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
$(window).on("load", function() {
$(".tabs2accordion").tabs2Accordion({
state: "desktop"
});
});
I rewrote your code following jQuery's Plugin creation standard.
http://codepen.io/justinledouxmusique/pen/GZrMgB
Basically, I did two things:
Moved away from using data attributes for styling (switched to using an .active class instead)
Moved away from using this everywhere, as it bring a whole wave of binding issues...
$.fn.tabs2Accordion loops through all the selectors, and applies $.tabs2Accordion. It also returns the selector for chaining (it's a standard in jQuery).
Then, all the internal methods are function expressions which are in the same scope as all your old this "variables". This simplifies the code greatly as you can refer to those variables without passing them in as a parameter or without having to .bind( this ) somehow.
Finally, the old init() function is gone. Instead, I put the code at the end of the $.tabs2Accordion function.
Hope this helps!
(function ( window, $ ) {
$.tabs2Accordion = function ( node, options ) {
var options = $.extend({}, {
menuSelector: '.tabs2accordion-menu',
tabContentSelector: '.tabs2accordion-content'
}, options )
var $element = $( node ),
$menu = $element.find( options.menuSelector ),
$tabs = $element.find( options.tabContentSelector ),
$accordionTriggers = $tabs.find( 'h3' )
var resizeTabs2Accordion = function () {
$element.outerHeight( !$element.is( '[data-nested-menu]' )
? $element.find( 'div.active' ).outerHeight() + $menu.outerHeight()
: $element.find( 'div.active' ).outerHeight() )
}
var showTabContent = function () {
var $this = $( this ) // This will be the clicked element
$menu
.find( '.active' )
.removeClass( 'active' )
$element
.find( '.active' )
.removeClass( 'active' )
$( $this.find( 'a' ).attr( 'href' ) )
.addClass( 'active' )
$this
.find( 'a' )
.addClass( 'active' )
resizeTabs2Accordion()
return false
}
var showAccordionContent = function () {
var $this = $( this ),
$parent = $this.parent(),
mobileIsActive = $parent.data( 'active-mobile' )
$( '[data-active-mobile]' )
.not( $parent )
.data( 'active-mobile', false )
$parent
.data( 'active-mobile', mobileIsActive ? false : true )
}
// The equivalent of init()
$tabs
.removeClass( 'active' )
.first()
.addClass( 'active' )
$element.addClass( 'loaded' )
$menu.on( 'click', 'li', showTabContent )
$( window ).on( 'resize', resizeTabs2Accordion )
resizeTabs2Accordion()
console.log( $element )
}
$.fn.tabs2Accordion = function ( options ) {
this.each( function ( index, node ) {
$.tabs2Accordion( node, options )
})
return this
}
})( window, jQuery )
$( window ).on( 'load', function () {
$( '.tabs2accordion' ).tabs2Accordion({
state: 'desktop'
})
})

jQuery contains from input text

I have simple jQuery function:
$(document).ready(function() {
$( "#faqsearch" ).keyup(function() {
var xyz = $( '#faqsearch' ).val();
$(".faqtitle:contains(xyz)").css("background","yellow");
});
});
Why I cannot get variable (in contains) from xyz?
you are passing the literal string of "xyz" instead of the variable xyz...
try changing it to:
$(document).ready(function() {
$( "#faqsearch" ).keyup(function() {
var xyz = $( '#faqsearch' ).val();
$(".faqtitle:contains(" + xyz + ")").css("background","yellow");
});
});
You can take advantage of the .filter() function:
$(document).ready(function() {
$( "#faqsearch" ).keyup(function() {
// If empty, clear backgrounds and stop
if(!$(this).val()) {
$(".faqtitle").css("background","none");
return false;
}
// Get string
var xyz = $(this).val();
$(".faqtitle")
.css("background","none") // Clear backgrounds
.filter(function() { // Filter for elements that contain xyz
return $(this).text().toLowerCase().indexOf(xyz) >= 0
}).css("background","yellow"); // Set background
});
});
See fiddle here: http://jsfiddle.net/teddyrised/9v8y7nvf/1/

tabs submiting form on new window, why?

I have an issue here.
I've been using Tabs (widget jqueryUi).
All seems to work fine, but sometimes when I submit a form (inside the tab), the result comes in the window and not in the tabdiv.
I don't want that, the client has to keep in the websystem.
I already tried putting target="_self" in the form, but keep doing the issue sometimes.
var $tabs = $("#main").tabs({
tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close notext inline'>Remove Tab</span></li>",
idPrefix: "tab_",
add:function(e, ui){
$tabs.tabs('select', '#' + ui.panel.id).show("blind");
$j( "#list_tabs .ui-icon-close:last" ).on( "click", function(e, elemento) {
var index = $( "li", $("#main").tabs() ).index( $( this ).parent() );
$("#main").tabs( "remove", index );
desativarItemSubmenu($('#' + $(this).parent()[0].id.replace('tab_', '')));
});
},
select: function(event, ui){
var id = $(ui.tab).parent()[0].id;
if(id)
ativarItemSubmenu($('#' + id.replace('tab_', '')));
},
cache:true,
ajaxOptions: {async: false,cache: false}
})
$(".anchor").live("click", function(){
if("<?php echo $this->session->userdata("cod_usuario") ?>" == ""){
window.location.reload;
}
var url = this.rel;
var tab_title = this.text;
var tab_id = "tab_"+this.id;
if(!$('#' + tab_id).length){
if($('#main').tabs('length') > 3)
$("#main").tabs("remove", 3);
$("#main").tabs("add", url, tab_title);
$("#list_tabs li:last").attr("id", tab_id);
$("#list_tabs li:last").addClass("active");
}
else{
$('#main').tabs('option', 'selected', $('#' + tab_id).index());
}
})
// Remove a tab clicando no "x" (remove tab by click on "x")
$( "#main span.ui-icon-close" ).live( "click", function() {
var index = $( "li", $("#main").tabs() ).index( $( this ).parent() );
$("#main").tabs( "remove", index );
});
I am not fully confident about this answer, but if not the solution then perhaps it will give you ideas that could lead to the solution.
It appears that you are changing the ID attribute of tabs on the fly. When you change an element's ID, you remove it from the DOM -- or rather, you re-inject it as a new element into the DOM. Therefore, any javascript that was previously bound to that element is no longer bound. Since you are using jQuery UI tabs, the changed element may stop being a tab.
This could cause the type of problem that you are describing.
Solution: instead of changing the tab ID, refactor your code to use classes that you add/remove.
As a general rule, use great caution when changing IDs on the fly.

JQuery dynamically added javascripts tags close button

I'm using javascript to dynamically add new tabs in jquery. I use the following code:
$("#mytabs1").tabs("add","list.action","New Tab");
My question is how i can add the close button (x button) to those dynamically added tabs?
There is actually an example to achieve this on the jQuery ui tabs demo pages.
Use the tabTemplate property:
HTML template from which a new tab is created and added. The
placeholders #{href} and #{label} are replaced with the url and tab
label that are passed as arguments to the add method
Here's the code from the site:
var $tabs = $( "#tabs").tabs({
tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove Tab</span></li>",
add: function( event, ui ) {
var tab_content = $tab_content_input.val() || "Tab " + tab_counter + " content.";
$( ui.panel ).append( "<p>" + tab_content + "</p>" );
}
});
// close icon: removing the tab on click
// note: closable tabs gonna be an option in the future - see http://dev.jqueryui.com/ticket/3924
$( "#tabs span.ui-icon-close" ).live( "click", function() {
var index = $( "li", $tabs ).index( $( this ).parent() );
$tabs.tabs( "remove", index );
});
In your implementation, you should not use .live() but delegate() or on(). Something like:
$('#tabs').on('click', 'span.ui-icon-close', function() {
var index = $( "li", $tabs ).index( $( this ).parent() );
$tabs.tabs( "remove", index );
});
Tabs do not inherently have an x button. If you are adding an x button to your tabs somewhere else, and would like this same x button added to new tabs you add, you could try using the tabsadd event:
$("#mytabs1").tabs({
add: function(event, ui) {
//your code that adds the custom x button to the new tab here
}
});
If you want to select immediately new added tab:
var $tabs = $('#tabsid').tabs({
add: function(event, ui) {
$tabs.tabs('select', '#' + ui.panel.id);
}
});
this will not work..

Categories