Parameter from <a href></a> to javascript - javascript

I have a <ul> <li> menu. When the <a> element inside the <li> is clicked, I need to run a Javascript function and this function needs some parameters like id or name. How can I do it? How can i send/retrieve parameters?
Example Javascript:
function addTab(title, uri) {
var tabNameExists = false;
$('#tabs ul li a').each(function(i) {
if (this.text == title) {
tabNameExists = true;
}
});
Example HTML:
<ul>
<li>W to set parameters
</ul>

link
function addTab(this)
{
$(this).attr('id');
$(this).attr('name');
}

Try
<a href="url" id="someUniqueID" title="SomeTitle" onClick = "addTab(this.title, this.href,this.id);" >link</a>

Your codes are not quite related to your question, anyway, here is the way:
<li>W to set parameters</li>
More logics can be made, depends on how you write some_js_function(id,name).
Note: If you want to fetch the attribute of the <a> or <li> tag , you can go with #PSR's answer.

Related

Menu active current page

I'm using Bootstrap (AdminLTE) and I want to make the current page's menu item active.
Problem is, I don't know how to do it.
I do have a few solutions in mind (besides changing it in every php file), like putting an IF statement for every link, which would be a terrible solution (I think).
<ul class="sidebar-menu">
<li class="header">HOOFD MENU</li>
<li class='treeview'>
<a href='#'>
<i class='fa fa-dashboard'></i> <span>Dashboard</span>
<span class='pull-right-container'>
<i class='fa fa-angle-left pull-right'></i>
</span>
</a>
<ul class='treeview-menu'>
<li><a href='account.php'><i class='fa fa-circle-o'></i>Account</a></li>
</ul>
</li>
</ul>
The above is part of the menu.
So the menu item (in this case Dashboard) and sub-menu item both have to become active.
Thanks in advance!
Try this. This was copied from other bootstrap admin template and modified for AdminLTE
<script>
$(document).ready(function() {
var url = window.location;
var element = $('ul.sidebar-menu a').filter(function() {
return this.href == url || url.href.indexOf(this.href) == 0; }).parent().addClass('active');
if (element.is('li')) {
element.addClass('active').parent().parent('li').addClass('active')
}
});
</script>
This solution work with sublevel menu. Need JQuery
<script type="text/javascript">
$(document).ready(function () {
var url = window.location;
var element = $('ul.sidebar-menu a').filter(function () {
return this.href == url || url.href.indexOf(this.href) == 0;
});
$(element).parentsUntil('ul.sidebar-menu', 'li').addClass('active');
});
</script>
In one simple line:
$("ul.sidebar-menu li a[href='"+document.location.pathname+"']").parents('li').addClass('active');
So you should always check to make sure the element exists so you don't get any errors and you can user jQuery's data attribute selector to easily target the correct links.
var href = window.location.pathname;
if( $(".sidebar-menu a[href='"+href+"']").length ) {
$(".sidebar-menu a[href='"+href+"']").parent('li').addClass('active');
}
If you are using absolute urls you may need to switch from .pathname to .href in the var

Getting the class name which triggered the event

I have a tag with below HTML :
<a href='#' class='create_account singup header-icon'>Create Account</a>
I am using a common click handler of the 3 button with Class create_account , member_login , product_service
Now inside the handler , I want the class name which triggered the click event, in best possible way (with minimal condition)
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class'));
/**
In case , user click on button with class `create_account` , I get in console
`create_account singup header-icon` , which is correct,
**but I want `create_account` i.e is the class which triggered the Click event**
*/
});
I would just create a separate click handler for each class, like so:
// Define all the required classes in an array...
var selectors = ["create_account", "member_login", "product_services"];
// Iterate over the array
$.each(selectors, function(index, selector) {
// Attach a new click handler per-class. This could be a shared function
$("."+selector).click(function(e) {
e.preventDefault();
alert(selector); // Logs individual class
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="create_account" href="">Create</a>
<a class="member_login" href="">Login</a>
<a class="product_services" href="">Services</a>
If you want you can abstract the shared logic out into another function, like this Fiddle
Alternative Approach with Data Attributes
<a href='#' class='action-trigger' data-action='Creation'>Create Account</a>
$('.action-trigger').click(function(){
console.log($(this).data('action'));
});
Retrieve Class Based on it Being First
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account , .member_login , .product_services').click(function(){
console.log($(this).attr('class').split(' ')[0]);
});
Alternative Approach with Parameters
<a href='#' class='create_account singup header-icon'>Create Account</a>
$('.create_account').click(function(){
MyFunction('CreateAccount');
});
$('.member_login').click(function(){
MyFunction('MemberLogin');
});
function MyFunction(type)
{
console.log(type);
}
$(this).attr('class');
This will always return the list of classes that the element has. You can actually include an 'id' attribute to the element to access it when clicked.
<a href='#' class='but' id='create_account'>Button 1</a>
$('.but').click(function(){
alert($(this).attr('id'));
});
Demo: https://jsfiddle.net/dinesh_feder/2uq5h03j/
There are good solutions put forth using an array of selectors, but here is a solution using the strings of the selectors and the classes of the triggering element.
It's unfortunate that .selector was removed in jQuery 1.9 or else this would be even simpler. The approach is to get the original selector as an array and intersect it with the array of classes on the triggering element. The result will be the class that triggered the event. Consider this example:
[".create_account", ".member_login", ".product_services"]
[".class1", ".class2", ".create_account"]
Their intersection is:
[".create_account"]
Here is working code:
var selector = '.create_account, .member_login, .product_services';
$(selector).on("click", { sel: selector.split(", ") }, function(e){
var classArr = $(this).attr("class").split(" ").map(function(a){ return "."+a; });
var intersect = $.map(e.data.sel,function(a){return $.inArray(a, classArr) < 0 ? null : a;});
alert(intersect[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 class2 create_account">class1 class2 create_account</button><br/><button class="class3 product_services class4">class3 product_services class4</button><br/><button class="class5 class6 member_login">class5 class6 member_login</button>
I would add the classes into an array and then iterate to it to see if our target has one of those into its class attribute :
var classes = ['.create_account' , '.member_login' , '.product_services'];
$(classes.join()).click(function(){
for(var i=0; i<classes.length; i++){
var classPos = $(this).attr('class').indexOf(classes[i].substring(1));
if(classPos>-1)
$('#result').html(classes[i]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='create_account singup header-icon'>Create Account</a>
<a href='#' class='member_login singup header-icon'>Member Login</a>
<a href='#' class='singup header-icon product_services'>product services</a>
<p id="result"></p>
Well, to take back the Manish Jangir .... example, if you have to retrieve only the concerned class, then why don't you test it? you use jquery so you can use "hasClass" don't you?
$('.create_account , .member_login , .product_services').click(function(e){
if($(this).hasClass('create_account')){
alert('create_account');
}
if($(this).hasClass('member_login')){
alert('member_login');
}
if($(this).hasClass('product_services')){
alert('product_services');
}
});
This is maybe not a "perfect solution" but it fits your requirements...^^
You can also do it this way with jquery :
$('body').on('click','.create_account',function(event){
alert('.create_account');
//do your stuff
});
$('body').on('click','.member_login',function(event){
//...
});
$('body').on('click','.product_services',function(event){
//...
});
this way you just have to add a block if you add a new class that needs an event on click on it... I do not see any more "specific" answer to your question... I always used to do it this way since the way I handle the event on classes can be really different...

I need jQuery to perform a task if two conditions are true

I need some help to put an if statement together using jQuery. I want to change the logo on my site, if two conditions are true.
Here is some pseudo code, hopefully explaining what i want to archive:
if(li hasClass active and data-menuid is equal to 0033){
change logo...
}
Here is a simple example of the menu structure:
<div id="menu">
<ul id="menu-primary">
<li class="menuactive" data-menuid="0011">
Test1
<ul class="menu-dropdown">
<li data-menuid="0022">Test2</li>
<li class="active" data-menuid="0033">Test3</li>
</ul>
</li>
<li data-menuid="0044">Test4</li>
<li data-menuid="0055">Test5</li>
</ul>
</div>
You can check the combination of class and Attribute Equals Selector [name="value"]
if($('li.menuactive[data-menuid="0033"]').length){
//Your code to change the logo
}
You can use $.fn.filter()
Reduce the set of matched elements to those that match the selector or pass the function's test.
var listMeetingCondition = $('li').filter(function(){
return $(this).hasClass('menuactive') && $(this).attr('data-menuid') == "0033"
});
if(listMeetingCondition.length){
//Your code to change the logo
}
if($('li:has(.menuactive[data-menuid="0033"])').length){
change logo...
}
Another workaround:
var $target = $('li', '#menu-primary');
if( $target.hasclass('active') && $target.data('menuid') == '0033' ){
// change logo
}

Cant get the value of <li data-*> element. Tried Javascript as well as Jquery

The following is my dropdown list.
<ul id="navBar" data-value="">
<li data-city-value="blore">Bangalore
<ul>
<li data-city-value="delhi">Delhi</li>
<li data-city-value="che">Chennai</li>
<li data-city-value="jaipur">Jaipur</li>
<li data-city-value="hyd">Hyderabad</li>
<li data-city-value="mum">Mumbai</li>
<li data-city-value="pune">Pune</li>
</ul>
</li>
</ul>
And the following are my methods I tried to access the data-city-value attribute.
Method 1)
var cityName = document.getElementById('navBar');
var city = cityName.getAttribute('data-city-value');
alert(city);
It alerts "null"
Method 2)
var cityName = document.getElementById('navBar');
var city = cityName.dataset.cityValue;
alert(city);
It alerts "undefined".
Method 3)
$('#navBar li').click(function() {
$(this).parent().data('value', $(this).data('cityValue'));
});
alert($('#city').data('value'));
It alerts "undefined".
I checked the syntax to get data value here
It would be of great help if you can help me find where I am doing mistake.
Thanks. :)
IN your first two methods you target the top ul with id navBar. In the third method you do $(this).parent() which again takes you to the ul element.
That element does not have the data-city-value attribute.
The jquery method should be
$('#navBar').on('click','li', function(e) {
var city = $(this).data('city-value');
alert(city);
return false;
});
Demo at http://jsfiddle.net/gaby/Mb7KS/
As pointed out by Gaby, you need to reach the element firts. Try this:
$('#navBar:first-child')
This is how you can iterate through your data-city-value attributes:
$('li[data-city-value]').each(function(index,element){
alert($(element).data('city-value'));
});
You can also check my jsFiddle example.
For click events:
$(document).ready(function()
{
$('li').click(function() {
alert($(this).data('city-value'));
return false;
});
});
You should return false because the top li element has inner elements and it was triggering inner li element click event.
My second jsFiddle demo.

Find specific element in jQuery's .each function and do something with it

Here is my markup:
<ul class="tab1">
<li><a href="http://site.com/some.html?param=1"></li>
<li><a href="http://site.com/some.html?param=2"></li>
<li><a href="http://site.com/some.html?param=3"></li>
...
</ul>
I'm trying to compare if the current window.location matches any of the list anchors, and if true, then I'd like to do something like addClass('active').
My code for checking the current location of the browser and getting the href parameters from the list elements:
// get current url parameter
var getBrowserUrl = document.URL.split('?')[1];
// get parameters of all the <li> anchors
jQuery('.tab1 a').each(function(){
var getElementUrl = jQuery(this).attr('href').split('?')[1];
if (getBrowserUrl == getElementUrl ) {
jQuery(this).addClass('active');
}
});
The jQuery(this) bit obviously isn't working, since 'this' will refer to all of the list elements.
How can i specify the matching list element?
I've tested your code and made a few modifications try the following:
<ul class="tab1">
<li><a href="http://site.com/some.html?param=1"/></li>
<li><a href="http://site.com/some.html?param=2"/></li>
<li><a href="http://site.com/some.html?param=3" /></li>
</ul>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function () {
// get current url parameter
var getBrowserUrl = document.URL.split('?')[1];
// get parameters of all the <li> anchors
$('.tab1 a').each(function () {
var getElementUrl = $(this).attr('href').split('?')[1];
if (getBrowserUrl == getElementUrl) {
$(this).addClass('active');
}
});
});
</script>
If you want better control of the items you are iterating through, add this to your .each function:
.each(function(index, value) { ... }
That way, value is the element you are looking to find.

Categories

Resources