avoid duplicated jQuery code? - javascript

I am a novice to jquery. I have a section with some items. on click over any item i want to open the modal form, so instead of creating multiple modal forms i created one modal and than using carousel inside it to go through the items.
Now if one clicks the 10th item i want to apply the carousel active class to the 10th item. For now i have given id to all of them and using following code for each item. But that is not a good approach.
I appreciate your help!
Thanks
$('.filtr-item .mod1').on('click',function(){
$('#menuCarousel').find('.active').removeClass('active');
$('.mod1_item').addClass('active');
});
$('.filtr-item .mod2').on('click',function(){
$('#menuCarousel').find('.active').removeClass('active');
$('.mod2_item').addClass('active');
});
$('.filtr-item .mod3').on('click',function(){
$('#menuCarousel').find('.active').removeClass('active');
$('.mod3_item').addClass('active');
});

Use a generic class and add a data-attribute
$('.filtr-item .mod').on('click', function() { // or just $('.filtr-item').on
$('#menuCarousel').find('.active').removeClass('active');
$('.' + $(this).attr("data-mod") + '_item').addClass('active');
});
.active {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="filtr-item"><a class="mod" data-mod="mod1">Activate Mod1</a></li>
<li class="filtr-item"><a class="mod" data-mod="mod2">Activate Mod2</a></li>
<li class="filtr-item"><a class="mod" data-mod="mod3">Activate Mod3</a></li>
</ul>
<hr/>
<div id="menuCarousel">
<div class="mod1_item">Mod1</div>
<div class="mod2_item">Mod2</div>
<div class="mod3_item">Mod3</div>
</div>
For a longer explanation why to use $(this).attr("data-mod") rather than $(this).data("mod"), please see comments and jQuery Data vs Attr?
UPDATE: If you cannot change the html, you will need to interrogate the class
var re = /\bmod(\d+)/; // finds modN
$('.filtr-item a').on('click', function() {
$('#menuCarousel').find('.active').removeClass('active');
var match = this.className.match(re),
num = (match) ? match[1] : "";
if (num) $('.mod' + num + '_item').addClass('active');
});
.active {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="filtr-item"><a class="mod1">Activate Mod1</a></li>
<li class="filtr-item"><a class="mod2">Activate Mod2</a></li>
<li class="filtr-item"><a class="mod3">Activate Mod3</a></li>
</ul>
<hr/>
<div id="menuCarousel">
<div class="mod1_item">Mod1</div>
<div class="mod2_item">Mod2</div>
<div class="mod3_item">Mod3</div>
</div>

If I am not wrong you want to use one function instead of three different function you are using. you can give a custom data field to html eg. data-demo= "mod1".
and use the below code:
$('.filtr-item').on('click',function(){
$('#menuCarousel').find('.active').removeClass('active');
$('.'+$(this).attr('data-demo')+'_item').addClass('active');
});

JsFiddle
Without Data mode you can try this way.
$('.filtr-item').on('click', function() {
var num = $(this).prop('class').split(' ')[1].split('mod')[1];
$('#menuCarousel').find('.active').removeClass('active');
var cls = ".mod" + num + '_item';
$(cls).addClass('active');
});

Related

Why jQuery selectable is not functioning properly?

I have an mvc project where I have implemented two jQuery selectable plugin like below:
The <HTML> code,
<div class="product-page-options">
<div class="pull-left">
<label class="control-label" style="font-weight:bolder">Size:</label>
<ol class="ui-selectable" style="width:auto" id="selectable">
#{
var size = Model.AvailableSizes.Split(',');
foreach (var item in size)
{
<li class="ui-selectable">#item</li>
}
}
</ol>
</div>
<div class="pull-left">
<label class="control-label">Color:</label>
<ol class="ui-selectable" style="width:auto" id="selectable1">
#{
var color = Model.AvailableColors.Split(',');
foreach (var clr in color)
{
<li class="ui-selectable">#clr</li>
}
}
</ol>
</div>
</div>
The static script for selectable jQuery plugin.
<script type="text/javascript">
$(document).ready(function () {
$("#selectable").selectable({
selected: function (event, ui) {
$(ui.selected).siblings().removeClass("ui-selected");
$("#selectedsize").val($("li.ui-selected").html());
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#selectable1").selectable({
selected: function (event, ci) {
$(ci.selected).siblings().removeClass("ui-selected");
$("#selectedsize").val($("li.ui-selected").html());
}
});
});
</script>
The first selectable jQuery plugin works perfectly while the second is not functioning properly. I mean I cannot select any item from the second selectable list and also the appearance is not same as the first one. The picture below shows clearly the problem.
Anything i can do about it? any help would be appreciated. Thanks in advance.
There's 2 issues at play here. Firstly, you will need to have styles set up specifically for both of the selectables (if you have based your code on the examples on the jQuery UI site. Secondly, upon selecting in the selector for the items, you will need to identify the path to the selected li element as a child of the relevant selectable.
$("#selectedcolor").val($("#selectable1>li.ui-selected").html());
The following plunker will show you it working :
Link To My Plunker

Targeting Multiple Elements with One Function

I have a function that assigns dynamic classes to my div's. This function is a that runs on the page. After the page loads, all 10 of my primary 's have classes ".info1" or ".info2" etc...
I am trying to write a Jquery function that changes the class of the div you click on, and only that one. Here is what I have attempted:
$(".info" + (i ++)).click(function(){
$(".redditPost").toggleClass("show")
});
I have also tried:
$(".info" + (1 + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
And
$(".info" + (i + 1)).click(function(){
$(".redditPost").toggleClass("show")
});
EDITED MY HTML: DIV RedditPost is actually a sibling to Info's parent
<div class="listrow news">
<div class="newscontainer read">
<div class=".info1"></div>
<div class="redditThumbnail"></div>
<div class="articleheader read">
</div>
<div class="redditPost mediumtext"></div>
</div>
My issue is two fold.
The variable selection for ".info" 1 - 10 isn't working because i doesn't have a value.
If I did target the correct element it would change all ".redditPost" classes instead of just targeting the nearest div.
Try like this.
$("[class^='info']").click(funtion(){
$(this).parent().find('.redditPost').toggleClass("show");
});
Alternative:
$('.listrow').each(function(){
var trigger = $(this).find("[class^='info']");
var target = $(this).find('.redditPost');
trigger.click(function(){
target.toggleClass("show");
});
});
Try this
$("div[class*='info']").click(function(){
$(this).parent().find(".redditPost").toggleClass("show")
});
Explanation:
$("div[class*='info'])
Handles click for every div with a class containing the string 'info'
$(this).parent().find(".redditPost")
Gets the redditPost class of the current clicked div
Since the class attribute can have several classes separated by spaces, you want to use the .filter() method with a RegEx to narrow down the element selection as follows:
$('div[class*="info"]').filter(function() {
return /\binfo\d+\b/g.test( $(this).attr('class') );
}).on('click', function() {
$(this).siblings('.redditPost').toggleClass('show');
});
.show {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="listrow news">
<div class="newscontainer read">
<div class="info1">1</div>
<div class="redditThumbnailinfo">2</div>
<div class="articleheader read">3</div>
<div class="redditPost mediumtext">4</div>
</div>
</div>

Replace an object by another object in the same frame in JavaScript?

I have created a list with to options on the homepage (index.html). The problem I am encountering is that when I run the code; if the user clicks on "list_row1" then "table1" shows up (everything works great), and after this if the user clicks on "list_row2" then "table2" shows up 100-200px below table1 (everything does not work great). I want table1 to simply be replaced by table2 and vice-versa in the same spot by the list (list_row1 and list_row2) option the person clicks on.
For example, I want a red circle to be replace by a black circle and vice versa..
Here is my index.html with JavaScript code below:
$(function(){
$('#list_row1').on('click',function(){
$('#table2').hide();
$('#table1').toggle();
});
$('#list_row2').on('click',function(){
$('#table1').hide();
$('#table2').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul class="list-group">
<div id = "list_row1">
<li class="list-group-item">Exhaust Temperature</li>
</div>
<div id = "list_row2">
<li class="list-group-item">Cylinder Pressure</li>
</div>
</ul>
</div>
<div id = "table1"></div>
<div id = "table1"></div>
Please check your code. you have two divs with same id
<div id = "table1"></div>
<div id = "table1"></div>
Your id is same for both the tables. this should be your code:-
<div>
<ul class="list-group">
<div id = "list_row1">
<li class="list-group-item">Exhaust Temperature</li>
</div>
<div id = "list_row2">
<li class="list-group-item">Cylinder Pressure</li>
</div>
</ul>
</div>
<div id = "table1">table1</div>
<div id = "table2">table2</div>
<script>
$(function(){
$('#list_row1').on('click',function(){
$('#table2').hide();
$('#table1').toggle();
});
$('#list_row2').on('click',function(){
$('#table1').hide();
$('#table2').toggle();
});
});
</script>
Here is an example of how you could toggle the two 'table' divs while also improving your markup: http://jsfiddle.net/8fr0484L/3/
Use <a> anchor tags inside your <li> list items instead of attempting to use divs. This will allow you to make use of the anchor tag's default clickable behaviour.
<ul class="list-group">
<li class="list-group-item"><a href='#' id='list_row1'>Exhaust Temperature</a></li>
<li class="list-group-item"><a href='#' id='list_row2'>Cylinder Pressure</a></li>
</ul>
In the code it might be worth hiding the 'table' divs in the beginning (on page load), assuming you don't know at that point what the user wants to view.
// hide the tables by default when page loads
$('#table1').hide();
$('#table2').hide();
$('#list_row1').on('click',function(event){
event.preventDefault(); // halt the anchor tag's default behaviour
$('#table2').hide();
$('#table1').show();
});
$('#list_row2').on('click',function(event){
event.preventDefault(); // halt the anchor tag's default behaviour
$('#table1').hide();
$('#table2').show();
});
<ul class="list-group">
<div id = "list_row1"><li class="list-group-item">Exhaust Temperature</li></div>
<div id = "list_row2"><li class="list-group-item">Cylinder Pressure</li></div>
</ul>
</div>
<div id = "table1">abc</div>
<div id = "table2">pqr</div>
<script>
$(function(){
$('#list_row1').on('click',function(){
$('#table2').css({
visibility : "hidden"
});
$('#table1').css({
visibility : "visible"
});
});
$('#list_row2').on('click',function(){
$('#table1').css({
visibility : "hidden"
});
$('#table2').css({
visibility : "visible"
});
});
});
</script>
Hi its a typo both of your table have same id 'table1'. And also a small suggestion hide both the table divs at the load itself. I'm posting the new JavaScript code below have a look.
$(function(){
$('#table2').hide();
$('#table1').hide();
$('#list_row1').on('click',function(){
$('#table2').hide();
$('#table1').toggle();
});
$('#list_row2').on('click',function(){
$('#table1').hide();
$('#table2').toggle();
});
});

Set the HTML by calling using its ID or Class

I have a list of menus like
<ul id="toc">
<li>Description</li>
<li>Messages</li>
<li><a class="job_content">Applicants</a></li>
</ul>
Then i have a div like
<div id="job_item35116" class="items">
</div>
Then i have some more divs like
<div id="#description35116">
</div>
<div id="#msg_body35116">
</div>
So i am trying to do is when i will click the list item then these div (#description35116) will be appended inside id="job_item35116". (One item at a time)
So can i append a div with its ID inside another div ??
I tried like
JS (But its not working)
$('.job_content').unbind('click').click(function(){
var href = $(this).attr('href');
var id = $(this).attr('id');
var job_item = '#job_item'+ id;
if($(job_item).children().length > 0 ){
$(".items").empty();
$(href).toggle();
}else{
$(href).toggle();
}
return false;
});
Try this:
$('#toc li').on('click','a',function(e){
e.preventDefault();
var id = $(this).attr('href');
var div = $('<div id="' + id + '"></div>');
$(div).text(id);
$('.items').append($(div));
});
FIDDLE DEMO
Working solution: http://jsfiddle.net/aT7pF/1/
Remove the "#" from you ID-names in the div. It makes you live more easy.
From a coder perspective: Just place blank text within the </li>-tags. you don't need a <a href/>. Instead add a custom attribute to your tags, eg divId which you use to store the value of the </div>. it makes more sense this way. With JQuery you can fetch the value which you stored in your custom attribute easily with .attr()
(Refactored) HTML:
<ul id="toc">
<li divId="description35116">Description</li>
<li divId="msg_body35116">Messages</li>
<li>Applicants
</li>
</ul>
<div id="job_item35116" class="items"></div>
<div id="description35116">description35116</div>
<div id="msg_body35116">msg_body35116</div>
Javascript:
$("#description35116").hide();
$("#msg_body35116").hide();
var divId = $(this).attr("divId");
/*
you can make this line shorter:
$("#job_item35116").empty().append("<div>" +$("#"+divId).html() + "<div>");
*/
// by doing this:
$("#job_item35116").html("<div>" +$("#"+divId).html() + "<div>");

Getting Id from Div Class Name in Jquery

this is my Html code
<div class="span12" id="test" style="width: 810px;">
<ul class="nav nav-tabs">
<li class="active">New Stream</li>
<li><a id="addspan" href="/#C" data-toggle="tab">+</a></li>
</ul>
<div class="tabbable">
<div class="tab-content" id="tabContent">
<div class="tab-pane active" id="tab1">
#Html.Partial("_NewStreamPartial",Model)
</div>
</div>
</div>
</div>
this my javascript
<script type="text/javascript">
$(function () {
var count = 2;
$('#addspan').click(function () {
var Id = $('.tab-pane active').attr('id');
});
});
</script>
I want to get Div Id whoes class name ".tab-pane active"(means i want to get active Div Id) how i can do this?
You can use dot to join classes in selector
Change
var Id = $('.tab-pane active').attr('id');
To
var Id = $('.tab-pane.active').attr('id');
It should be like this,
var Id = $('.tab-pane.active').attr('id');
You are using Descendant Selector here. but in your dom both classes are in same element. so you have to select by both classes.
You can try this
$('.tab-pane active').click(function () {
var Id = $(this).attr('id');
});
Hope this helps
Try this :
$('#addspan').click(function () {
alert($('.tab-pane .active').attr('id'));
});
You can get any HTML Attribute from an element with jQuery's .attr():
$('.tab-pane.active').attr('id');
Similarly, you can also get the JS Object Property value using .prop():
$('.tab-pane.active').prop('id');
Try the following code
$("#addspan").click(function(){console.log($(this)[0].id);});

Categories