jQuery increase number depending on number of elements - javascript

Fiddle: http://jsfiddle.net/6vxe8qyj/
I've written a bit of script that adds a new attribute called trackingID that takes the title of each element and adds it into a tracking string.
The above works fine.
<a class="banner" title="This Is mainBanner 1"></a>
Would be:
<a class="banner" title="This Is mainBanner 1" trackingid="MAINBANNER-_-BANNER-_-This+Is+mainBanner+1"></a>
However, I've hit a bit of a bump as I'd like the BANNER section of the string to be numbered. i.e. BANNER+1 - BANNER+2
I then have a second set of banners (#secBanners) that I need to start back at 1 again.
I'm currently getting undefined and am unsure how to continue.
Any help would be great!
Thanks

Using your current methodology of things (EXAMPLE):
JS
$('a').attr("trackingID", " ");
function tracking(element, attr, attrVal, track, i) {
track.each(function () {
var $this = $(this),
trackRegEx,
newVal = attrVal.replace(/\[intBanner\]/g, i);
$this.attr(attr, newVal);
if ($this.attr('title') !== undefined && $this.attr('title') !== '') {
trackRegEx = $this.attr('title').replace(/ /g, '+');
$this.attr('trackingID', $this.attr('trackingID') + trackRegEx);
}
i++;
});
}
tracking($('#mainBanners a'), 'trackingID', 'MAINBANNER-_-BANNER[intBanner]-_-', $('#mainBanners a[trackingID]'), 0);
tracking($('#secBanners a'), 'trackingID', 'PROMOBANNER-_-BANNER[intBanner]-_-', $('#secBanners a[trackingID]'), 0);

Is this what you wanted?
Demo#Fiddle
$(".banner").each(function() {
var title = this.title.replace(/\s+/g, "+");
$(this).attr({
"trackingid": "MAINBANNER-_-BANNER+" + title.slice(-1) + "-_-" + title
});
});
P.S. please do your other checks, such as empty/undefined etc. as you please.

This will do what you requested:
$('#mainBanners a.banner').attr('trackingID',function(i){
return 'MAINBANNER-_-BANNER+' + (i+1)
});
$('#secBanners a.banner').attr('trackingID',function(i){
return 'PROMOBANNER-_-BANNER+' + (i+1)
});
http://jsfiddle.net/6vxe8qyj/4/

Related

jQuery working with dynamic elements

I have so much problem working with dynamic elements in jQuery, that I just need to ask a question. First, a little example from my system:
main.js
$(function () {
renderPlaceList(places);
setupVoting();
}
The two function are in separate files, renderPlace.js is a file, where I am creating a new elements. These elements have class .option and they are then stored in a .places div. So far so good. But then I want to work with these elements in setupVoting():
$('.participants .option').each(function () {
...
})
But this just doesn't seem to be working. When I call the code in browser console, it runs just fine. But if it's run while the site is loading, the jQ selector won't find the elements. Where is the catch?
Thanks for your time and answers :)
EDIT
renderPlaces function
function renderPlaceList(places) {
var htmlMeetingPlace = "";
into = $(".places");
$(places).each(function(_, d){
htmlMeetingPlace +=
"<div class='option' data-meeting_place_id='" + d.id + "'>" +
"</div>";
});
into.fadeOut('slow',function(){
into.html("");
into.append(htmlMeetingPlace);
into.fadeIn('slow');
});
}
Problem is that when renderPlaceList return.. $(".places") is not enought formated.. because is still fadeouting..
You can try
function renderPlaceList(places) {
var htmlMeetingPlace = "";
into = $(".places");
$(places).each(function(_, d){
htmlMeetingPlace +=
"<div class='option' data-meeting_place_id='" + d.id + "'>" +
"</div>";
});
into.fadeOut('slow',function(){
into.html("");
into.append(htmlMeetingPlace);
into.fadeIn('slow');
setupVoting(); //here!
});
}

Basic Slideshow

I am creating a slideshow in JavaScript and jQuery to show an array of images.
My idea is to put 3 divs on the page:
One with a left button
one with a right button
one called screen that will display the image.
This is the code I have written, but I don't know what's missing. Maybe an onload event?
var now =0;
var image_array=
[
"../cabinets/001.jpg",
"../cabinets/002.jpg",
"../cabinets/003.jpg"
];
$("#left").click(left( if(now<image_array.length)
{
now++;
$('#screen').css('background-image', 'url("' + array[now] + '")');
}));
$("#right").click( if(now>0)
{
now--;
$('#screen').css('background-image', 'url("' + array[now] + '")');
});
I rewrote your code, here is result:
1) have you included jQuery library into your project?
2) in your jQuery code in lines:
$('#screen').css('background-image', 'url("' + array[now] + '")');
you using bad array name array[now], your array is image_array, so you must rewrite this into image_array[now]
3) your definition of .click function is not correct. You must define it as: .click(function(){ ... });, so your lines will look like:
// left click
$("#left").click(function(){
if(now > 0){
now--;
}
$('#screen').css('background-image', 'url("' + image_array[now] + '")');alert(now);
});
and
// right click
$("#right").click(function(){
if(now < image_array.length-1){
now++;
}
$('#screen').css('background-image', 'url("' + image_array[now] + '")');alert(now);
});
Here is working JSFiddle solution: JSFiddle
Here is the second solution with updated IF terms: JSFiddle

adding attribute to url for Summernote

I am using summernote and I am having trouble adding attributes to Link. How can I add target="_blank" rel="nofollow" to the inserted url?
I have found this line, somewhere on line 977:
sLinkUrlWithProtocol = sLinkUrl.indexOf('://') !== -1 ? sLinkUrl : 'http://' + sLinkUrl;
I have tried adding +'target="_blank"' to the end. The result was garbage, showing this:
http://sample.comtarget%3D%27_blank%27/
My full (probably working) solution =] Lines 980 - 989
//IE: createLink when range collapsed.
if (agent.bMSIE && rng.isCollapsed()) {
rng.insertNode($('<A target="_blank" id="linkAnchor">' + sLinkUrl + '</A>')[0]);
var $anchor = $('#linkAnchor').removeAttr('id')
.attr('href', sLinkUrlWithProtocol);
rng = range.create($anchor[0], 0, $anchor[0], 1);
rng.select();
} else {
document.execCommand("insertHTML",false,'<a target="_blank" href="'+sLinkUrlWithProtocol+'">'+sLinkUrl+'</a>');
}

jQuery(...).val(...).xxx is not a function

I want to use EggImageDropdown, but I have problems with the script.
I embedded it in my testing site and there it works:
http://herzschloss.de/hs/test.php at "Mein Wunschbild".
Now I want to use the same script with the same linked in js-code here:
http://herzschloss.de/Liebesschloss-bestellen at "Mein Wunschbild"
But I get an error.
TypeError: jQuery(...).val(...).EggImageDropdown is not a function
This is the live generated script that didn't work:
function onclick(event) {
var t = jQuery('select[id=dropdown_demo]').val('herz.png').EggImageDropdown('close').EggImageDropdown('update',{src:'hs-motive/herz.png'});t.trigger('change');
}
This is the code:
jQuery('option',element).each(function(i,el){
dropdown.append('<img style="width:100%" onclick="var t=jQuery(\'select[id=' + selectName + ']\').val(\''+ $(el).val() + '\').EggImageDropdown(\'close\').EggImageDropdown(\'update\',{src:\''+ $(el).text() + '\'});t.trigger(\'change\');" src="' + $(el).text() + '"/>');
});
It would be great if you help me!
It's very difficult to embed that much code into an onclick attribute. Better to not do it.
To correct it, create the function directly in the loop instead of creating an attribute.
jQuery('option',element).each(function(i,el){
var img = $('<img>', {style: "width:100%;", src: $(el).text()});
img.click(function() {
var t=jQuery('select[id=' + selectName + ']');
t.val($(el).val()).EggImageDropdown('close')
.EggImageDropdown('update', {src:$(el).text()});
t.trigger('change');
});
dropdown.append(img);
});
Furthermore, looking at your linked site, it appears that the EggImageDropdown function doesn't exist, which means you're not successfully loading the plugin.

jquery get rel attribute and change it

Hey guys, I have the following code. It is basically a gallery script and when I mouse over the thumbnail, it will change the a bigger version of the thumbnail:
$.fn.CloudZoom = function (options) {
try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e) {}
this.each(function () {
var relOpts, opts;
eval('var a = {' + $(this).attr('rel') + '}');
relOpts = a;
if ($(this).is('.image')) {
$(this).css({
'position': 'relative',
'display': 'block'
});
$('img', $(this)).css({
'display': 'block'
});
if ($(this).parent().attr('id') != 'imageBox') {
$(this).wrap('<div id="imageBox"></div>');
}
opts = $.extend({}, $.fn.CloudZoom.defaults, options);
opts = $.extend({}, opts, relOpts);
$(this).data('zoom', new CloudZoom($(this), opts));
} else if ($(this).is('.thumbs')) {
opts = $.extend({}, relOpts, options);
$(this).data('relOpts', opts);
$(this).bind('mouseenter click', $(this), function (event) {
var data = event.data.data('relOpts');
$('#' + 'mainImage').data('zoom').destroy();
$('#' + 'mainImage').attr('href', event.data.attr('href'));
// Change the small image to point to the new small image.
$('#' + 'mainImage' + ' img').attr('src', data.thumby);
$('#' + 'mainImage').CloudZoom();
return false;
});
}
});
return this;
};
The html reads as follows:
<li>
<a href="gfx/boss_black.jpg" class="thumbs" rel="thumby:'gfx/boss_black.jpg'">
<img src="gfx/boss-black-small.jpg">
</a>
</li>
What I want to do is to write the rel="" tag without the "thumby".
I want the rel tag look like this:
rel="gfx/boss_black.jpg"
When I do this, the JS doesn't work anymore. How do I change the JS to simply get the "rel"?
var img = $('#' + 'mainImage' + ' img'),
rel = img.parent().attr('rel'),
thumby = rel.substr(8, rel.length - 9);
img.attr('src', thumby);
I would recommend storing the alternative src attribute in an attribute other than rel though. A HTML5 data attribute would be a good candidate.
Also, that is a bizarre selector :)
If I understand correctly - there is a library called thumby that requires a special format for your rel tag that you do not want in your source.
I can see two possible soultions.
Try to execute the javascript that changes the rel tag before the thumby library is included. Javascript loads and executes in the order specified in your HTML document. Hopefully thumby will pick up the changed value, but the source html contains the old value.
Modify the thumby library - specifically the part that reads from rel, and maybe make it identify where to operate based on the class thumbs instead.
Something like:
<li>
<a href="gfx/boss_black.jpg" class="thumbs">
<img src="gfx/boss-black-small.jpg" rel="gfx/boss_black.jpg">
</a>
</li>
...
$('.thumbs img').hover(
function () {
var r = $(this).attr('rel'), a = $(this).attr('src');
$(this).attr({'rel':a,'src':r});
},
function () {
var r = $(this).attr('rel'), a = $(this).attr('src');
$(this).attr({'rel':a,'src':r});
}
);

Categories