Shorten jquery script - javascript

Sorry for asking, but i am really newbie in jquery.
$(".productTopMenu").click(function() {
$("#breadcrumbs").html("Home / <strong>Product</strong>");
});
$(".downloadTopMenu").click(function() {
$("#breadcrumbs").html("Home / <strong>Download</strong>");
});
this is a breadcrumbs. every .productTopMenu clicked, #breadcrumbs will call the text.
if there is 15 pages, i must put 13 more copies of that script.
how to shorten that script like :
.productTopMenu = Home / <strong>Product</strong>
.downloadTopMenu = "Home / <strong>Download</strong>
the text always called inside #breadcrumbs.
is there a way to shorten this script ?
thanks in advance
any suggestion are welcome.

Something like:
$('[class$="TopMenu"]').click(function() {
$("#breadcrumbs").html("Home / <strong>" + getNameFromClass(this.className)
+ "</strong>");
});
function getNameFromClass(theClass) {
// take substring and make title case here
}

I haven't tested it but this should work:
// your data as an array containing objects
var item = [
{
"selector" : ".productTopMenu",
"label" : "Product"
},
{
"selector" : ".downloadTopMenu",
"label" : "Download"
}
],
i = item.length - 1,
$breadcrumbs = $('#breadcrumbs'); // Dom Cache
while (i >= 0) {
(function (i) {
$(item[i].selector).click(function () {
$breadcrumbs.html('Home / <strong>' + item[i].label + '</strong>');
});
}(i));
}

As everyone else has suggested, take the name from an existing element, and then use common class to hook up the click delegate.
If you haven't got the text as it should appear, you could try outputting it as a data-* attribute...
<a href="#" data-title="Downloads" />Go to Downloads</a>
That way you can control the name separately from everything else, at least.

You can give each of this menu elements the same calls, a unique ID and have a mapping id -> text:
var paths = {
'productTopMenu': "Home / <strong>Product</strong>",
'downloadTopMenu': "Home / <strong>Download</strong>"
};
$('.menuItem').click(function() {
if(paths[this.id]) {
$("#breadcrumbs").html(paths[this.id])
}
});
DEMO
You could also use a data- attribute to store some identifier, it does not have to be the id attribute.
Of course there are other ways. You have to decide how automatic or flexible you want the solution to be.

Try to use .each()

Related

Making part of an Id name into a variable

I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});

Two different css classes in the same javascript line

I'm trying to assign these css values (below) for the javascript line in the example below, but don't know a way to target valueB with the .valueB-class.
$(".valueA").html(valueA + " valueB" + ((valueA > 1) ? 's': ''));
.valueA-class { font-size:X }
.valueB-class { font-size:XX }
Here is an example of what I need help with (you may have to click on the input boxes in the results panel to get the calculations to show up - that's what I had to do): http://jsfiddle.net/hughett/g21g8t85/
Welcome to stackoverflow!
Your question seems a bit vague. I assume that this is you want to achieve. In the specific example the value of the class is changed through the use of the jquery attr function. Firstly, the specific div in which our text is placed is retrieved and then the value gets specified. I am attaching a code snippet below.
A general note, using a . in css indicates that you are referring to a class so there is no need to attach a -class in the name.
$( "#myButton" ).on( "click", function() {
var attr = $("#myText").attr('class');
console.log(attr);
if (attr == "valueA") {
$("#myText").attr("class","valueB");
} else {
$("#myText").attr("class","valueA");
}
});
.valueA { font-size:11pt }
.valueB { font-size:25pt }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Change Text size</button>
<div id="myText" class="valueA">sdsa asd aasdaas asdjlasj dasdkas asldjsalj slad TEST</div>
EDIT to include another answer
In order for the text included in a single span to have different font-size you need to separate it somehow. In the specific example, I have added a second span in the respective div and adjusted the cacl_summary method to get the expected result.
The code is available below; I have also updated the jsfiddle here
<div style="background:yellow;"><span class="label">Simple payback</span>
<span class="figure sp"></span> <span class="figure year"></span></div>
function calc_summary(){
if (cspy) {
sp = parseFloat($("input[name=upgrade]").val()) / cspy;
if (sp) {
sp = (sp < 100) ? sp.toString().substring(0, 4) : sp;
$(".sp").html(sp);
$(".year").html(" years" + ((sp > 1) ? 's': ''));
$(".ror").html(parseInt((1/sp) * 100) + '%');
}
}
}

How do you create variables to open up the same type of div?

I am making a website that displays profiles of people. Each person is designated a svg button and when that button is clicked, a pop up displays that persons information.
I have this jquery function:
$('.button1').click(function() {
$('.person1-profile').fadeIn();
});
$('.button1-exit').click(function() {
$('.person1-profile').fadeOut();
});
$('.button2').click(function() {
$('.person2-profile').fadeIn();
});
$('.button2-exit').click(function() {
$('.person2-profile').fadeOut();
});
$('.button3').click(function() {
$('.person3-profile').fadeIn();
});
$('.button3-exit').click(function() {
$('.person3-profile').fadeOut();
});
I'm wondering if it is possible to do this with Javascript so that it significantly shortens the coding, and rather than copy & pasting that code every time for each person, if variables can be made for people/profile and so it would be something like:
$('var person + button').click(function() {
$('var person + profile').fadeIn();
});
$('var button + exit').click(function() {
$('var person + profile').fadeOut();
});
Thank you I really appreciate it! Sorry if it is unclear.
You could use data-attributes for this one:
Define your buttons like that:
<button class="openButton" data-person="3">Open</button>
<button class="closeButton" data-person="3">Close</button>
And your open/close-code like that:
$('.openButton').click(function() {
var personNumber = $(this).attr("data-person");
$('.person'+personNumber+"-profile").fadeIn();
});
$('.closeButton').click(function() {
var personNumber = $(this).attr("data-person");
$('.person'+personNumber+"-profile").fadeOut();
});
In action: http://jsfiddle.net/ndx4fn9n/
I can think of few ways of doing it.
You could read only 7th character of the class name. This limits you to having only 10 fields. Or you could put id on very end like this person-profile1 and read 16th and up character.
You could also set up additional tag to your container. But this will cause your web page to not HTML validate.
<div class="person" personid="1">// content</div>
You can do this in your selector:
var buttons = document.getElementsByTagName(svgButtonSelector);
for (i = 0; i > buttons.length; i++) {
$(".button" + index).click(function() {
$(".person" + index + "-profile").fadeIn();
});
}
This will attach the event to every svg button you've got on your page. You just gotta make sure the scope of selection for the buttons is declared right (I'm using document as an example).

How do I pass data from a link to a jQuery function?

$(function(){
$('.tab2').live('click', function() {
$('#coverTextH3').text(data[1].H3)
$('#coverTextP').text(data[1].P)
});
});
Lets say I have a link How do I pass data, the index of an array, to a jQuery function so I do not have to repeat my code, for each index [0]-[7]?
var data = [
{
H3: 'name',
p: 'more'
},
{
H3: 'string',
p: 'more strings'
}]
There are numerous options. If attaching handlers via javascript, I would select basing on element's id or some custom attribute, not the class. So say you have a number of links like this:
Tab 1
Tab 2
Tab 3
javascript in this case would be
$(function(){
$('a[link-number]').live('click', function() {
var index = $(this).attr('link-number') * 1 - 1;
$('#coverTextH3').text(data[index].H3)
$('#coverTextP').text(data[index].P)
});
});
Alternatively, you can attach click handlers right in your a elements declaration:
Tab 1
Tab 1
Tab 1
and define setCover function like this:
function setCover(index) {
$('#coverTextH3').text(data[index].H3)
$('#coverTextP').text(data[index].P)
}
Each of alternatives require changes in your htlm. If for some reason it is not possible, you need to at least now the range of your tabs, which can be quite tricky.
Something similar to this should work:
markup:
<a href="www.link.com" data-index="1" id="link1" />
javascript:
$(function(){
$('#link1').live('click', function() {
var idx = $(this).data('index');
$('#coverTextH3').text(data[idx].H3)
$('#coverTextP').text(data[idx].P)
});
});
if your link IDs correspond to the index order in the array you can do something like this:
example jsfiddle
jQuery:
$(function() {
$('.tab2').live('click', function(e) {
e.preventDefault();
// parse the integer from the ID
// and get the 0-based index (by subtracting 1)
var idx = $(this).attr('id').replace('link', '') * 1 - 1;
$('#coverTextH3').text(data[idx].H3)
$('#coverTextP').text(data[idx].p)
});
});
HTML:
Link 1
Link 2
<h3 id="coverTextH3"></h3>
<p id="coverTextP"></p>
Text
I'm not sure I understand exactly what you're asking. If this doens't fit, please clarify.

regarding a piece of code

i want to understand this piece of code as i m a beginner.Mostly these red color fonts. they are taking which page value?
$(function() {
$("#title").blur(function() { QuestionSuggestions(); });
});
function QuestionSuggestions() {
var s = $("#title").val();
if (s.length > 2 && !($("#title").hasClass('edit-field-overlayed'))) {
document.title = s + " - Stack Overflow";
$("#question-suggestions").load("/search/titles?like=" + escape(s));
}
}
function QuestionSuggestions() {
var s = $("#title").val(); // Here we take the value of element with ID "title"
// If the length of the title is bigger than 2 or
// the element doesn't have 'edit-field-overlayed' class
if (s.length > 2 && !($("#title").hasClass('edit-field-overlayed'))) {
// we set the title of the document as <title>[our old title] - Stack Overflow</title>
document.title = s + " - Stack Overflow";
// Load data from the server and place the returned HTML into the matched element.
$("#question-suggestions").load("/search/titles?like=" + escape(s));
}
}
If you element with id title has longer title than 2, lets say "My title" and there is no class "edit-field-overlayed" we change the page title to "My title - Stack Overflow" and load html/text in element "#question-suggestions" by querying the URL http://yoursite.tld/search/titles?like=My%20title
This looks like jQuery code. The expression $("#title") is a call to the jQuery $ function. It looks for the HTML tag with id="title" and wraps a utility object around it. .blur is a method of that utility object, which supplies a function to be called when the mouse moves off the corresponding element.
The best thing would be to get stuck into a jQuery tutorial like this one.
The peice of code posted, condensed to a sentence is
"When the field with id 'title' blurs, execute an ajax query passing the content of that field as a parameter"

Categories