How to get img src attribute from an ul of images? - javascript

<ul id="ulGall">
<li><img src="gaLL/red.jpg"/></li>
<li><img src="gaLL/blue.jpg"/></li>
<li><img src="gaLL/white.jpg"/></li>
<li><img src="gaLL/orange.jpg"/></li>
</ul>
.
$(document).ready(function() {
x = 0;
z = $('#ulGall li').length;
});
.
$('#btnR').click(function() {
if(x == z) {x = 1;}
else {x = x + 1;} // till here everything works
alert ($('ulGall').index =x, src attribute // just as description
i.e. - give me img src attribute - where li index = x
So first click should be gaLL/red.jpg
Next click - gaLL/blue.jpg and so on
After orange - red again.

I thought I'd offer an alternative, despite your having an already-accepted answer:
function clicks(el){
if (!el) {
return false;
}
else {
var i = 0;
clicks = function(el){
var kids = $(el).find('img').length,
which = i < kids ? i : i%kids;
console.log($(el).find('img').eq(which).attr('src'));
i++;
};
clicks(el);
}
}
$('#ulGall').click(
function(){
clicks(this);
});​
JS Fiddle demo.
And a slightly-revised, less-jQuery, function:
function clicks(el) {
if (!el) {
return false;
}
else {
var i = 0;
clicks = function(el) {
var imgs = el.getElementsByTagName('img'),
kids = imgs.length,
which = i < kids ? i : i % kids;
console.log(imgs[which].src);
i++;
};
clicks(el);
}
}
JS Fiddle demo.

You can get the "src" attribute of the img inside the first li like this:
$("#ulGall li").eq(0).next("img").attr("src");
The number in the .eq() function determines which of the li elements is targeted - with the first having an index of 0.

$('#btnR').click(function() {
if(x == z) {x = 1;}
else {x++}
var source=$("#ulGall li").eq(x).next("img").attr("src");
alert(source);
});
The trick here is using .eq() which selects the element based on it's index, you can also select an element by index directly from the selector like so:
$("#ulGall li:eq(0)")

You can use the :eq selector of jQuery.
$('#ulGall li:eq(0) img').attr('src')​

For the sake of completeness, it seems that a good jQuery alternative is missing here.
$('button').each(function(){
var idx = 0, $gallery = $("#ulGall").find("img");
$(this).click(function(){
var src = $gallery.eq(idx).attr("src");
idx = (idx == $gallery.length - 1) ? 0 : idx + 1;
});
});​
A live example.

Related

Change page name based on the tab

Im having a small app built using jquery mobile and nativedroid2.
I would like to know if its possible to change the page heading name based on the tab name?
For an example http://jsfiddle.net/livewirerules/2a7so7r5/1/ You will see the page heading is Friends and my active tab is Friends so when i move to the next tab. Work the page title should change accordingly
Below is my demo JS code
$(document).on("pagecreate", "#page1", function () {
$("div[role=main]").on("swipeleft", function (event) {
changeNavTab(true);
});
$("div[role=main]").on("swiperight", function (event) {
changeNavTab(false);
});
});
function changeNavTab(left) {
var $tabs = $('ul[data-role="nd2tabs"] li');
console.log($tabs);
var len = $tabs.length;
var curidx = 0;
$tabs.each(function(idx){
if ($(this).hasClass("nd2Tabs-active")){
curidx = idx;
}
});
var nextidx = 0;
if (left) {
nextidx = (curidx >= len - 1) ? 0 : curidx + 1;
} else {
nextidx = (curidx <= 0) ? len - 1 : curidx - 1;
}
$tabs.eq(nextidx).click();
}
any help will be appreciated
You want to attach to the click handler of each tab item. Just add this block of code to your $(document) function. And set an id for your page heading element.
<h1 id="heading" class="wow fadeIn" data-wow-delay='0.4s'>Friends</h1>
$('ul[data-role="nd2tabs"] li').on('click',function(){
$("#heading").html($(this).html());
});
Here's the updated fiddle
http://jsfiddle.net/2a7so7r5/18/
I don't know what expected but this is my aproach
Modified example
function changeNavTab(left) {
var $active = $('ul[data-role="nd2tabs"] li.nd2Tabs-active');
if(left){
var $moveto = $active.next().length ? $active.next() : $('ul[data-role="nd2tabs"] li:first');
}else{
var $moveto = $active.prev().length ? $active.prev() : $('ul[data-role="nd2tabs"] li:last');
}
var title = $moveto.text();
$("h1.ui-title").text(title);
}

Changing CSS URL for pointer cursor (using Javascript)

I asked a question yesterday here about having a cursor that changes regularly using javascript, to make it look animated. I got a great answer (Thank you Shiva!). I've now been trying to get two different 'animated' cursors, one for the 'auto' cursor, and a different one for the 'pointer' cursor.
I tried it lots of different ways, but just can't work it out (I must admit, I'm completely new to this - trying to improve). Here's one of the ways I tried to do it:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
var images = [
'assets/shared/cursors/drum1.cur',
'assets/shared/cursors/drum2.cur',
'assets/shared/cursors/drum3.cur',
'assets/shared/cursors/drum4.cur'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 250);
</script>
<script type = "text/javascript">
var images = [
'assets/shared/cursors/point1.cur',
'assets/shared/cursors/point2.cur',
'assets/shared/cursors/point3.cur',
'assets/shared/cursors/point4.cur'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor:pointer = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 250);
</script>
<body>
<div style="height: 1000vh; width: 1000vw;"></div>
</body>
</html>
</head>
</html>
If possible I'd like to do it without jQuery.
Again, any help is really appreciated.
Thanks! :)
You can try using jQuery for this :
var images = [
'assets/shared/cursors/point1.cur',
'assets/shared/cursors/point2.cur',
'assets/shared/cursors/point3.cur',
'assets/shared/cursors/point4.cur'
];
var x = 0;
function changeLinkCursorHoverBinding(){
$("a").hover(function(){/*this is the mouseenter triggered function*/
$(this).css("cursor",'url("' + images[x] + '"), default');
}, function(){
//handle mouseleave here if needed
});
x = (x === images.length - 1) ? 0 : x + 1;//put at the end to start at 0
setTimeout(changeLinkCursorHoverBinding, 250);
}
$(document).ready(changeLinkCursorHoverBinding);//initial call of the function
EDIT
Or without jQuery :
var images = [
'assets/shared/cursors/point1.cur',
'assets/shared/cursors/point2.cur',
'assets/shared/cursors/point3.cur',
'assets/shared/cursors/point4.cur'
];
var x = 0;
function changeLinkCursorHoverBinding(){
var elems = document.querySelectorAll("a");
elems.removeEventListener("mouseenter", onHover);
elems.removeEventListener("mouseleave", offHover);
elems.addEventListener("mouseenter", onHover);
elems.addEventListener("mouseleave", offHover);
x = (x === images.length - 1) ? 0 : x+1;
setTimeout(changeLinkCursorHoverBinding, 250);
}
function onHover(){
var elems = document.querySelectorAll("a");
for(e in elems){
e.style.cursor = "url('" + images[x] + "'), default";
}//you can use the regular for loop here if you wanna
}
function offHover(){
var elems = document.querySelectorAll("a");
for(e in elems){
/*handle mouseleave here*/
}
}
I had to name EH functions (and remove EH each call) because I wasn't sure that addEventListener overrides same handler if called again.
EDIT
for non jQuery way, you need to add onload="changeLinkCursorHoverBinding()" on your <body> tag this way :
<body onload="changeLinkCursorHoverBinding()"> (the initial call after page's load).

Split a big ul list

I have a big ul list. With a lot of li items. I want split this big list in parts of 10. I make a script, but the script is not working. What do i wrong:
var maxItems = 10;
var ul = $('.list-thumbnails');
var current;
ul.find('li').each(function(i, el) {
  if (i < maxItems) {
    // leave first 10 in the original list
    return;
  }
  if (i % maxItems == 0) {
    current =
        $(el)
            .closest('ul')
            .clone()
            .after($(el).closest('ul'));
  }
.append(current);
});
I have modified the code block as below. Please check it
Since your looping the $.each though you use append method it won't get reflected in the ul and so we need to remove the element.
var maxItems = 10;
var ul = $('.list-thumbnails');
var currentul;
var elements = ul.find('li');
elements.each(function (i, el) {
if (i < maxItems) {
// leave first 10 in the original list
return;
}
if (i % maxItems == 0) {
currentul = $("<ul></ul>").addClass("new");
$(el).closest('ul').parent().append((currentul.append(el)));
}
else {
currentul.append(el)
}
});
$('.list-thumbnails').find("li:gt(9)").remove();
Please check the below jsfiddle
http://jsfiddle.net/aQ5K8/13/
Thanks
Sridhar

Make a jQuery slider work with divs instead of images

I am working on this website page poochclub.com and I am trying to make all of it text instead of images. The problem is when I want to work on the panels below with all the information the js file (called about.js) is set to work with images instead on divs where I could potentially add text.
I am not very good at writing javascript and I need help to fix the original file which looks as follows:
<script type="text/javascript>
(function ($) {
var pages, panels, arrows, currentClass = 'current',
currentIndex = 0, currentSize = 0;
function showPage() {
var ctx = jQuery.trim(this.className.replace(/current/gi, ''));
$(this).addClass(currentClass).siblings().removeClass(currentClass);
$('.panel')
.removeClass(currentClass)
.find('img')
.removeClass(currentClass)
.removeAttr('style')
.end();
panels.find('.' + ctx)
.addClass(currentClass)
.find('img')
.removeClass(currentClass)
.removeAttr('style')
.eq(0)
.fadeIn()
.addClass(currentClass)
.end()
currentIndex = 0;
currentSize = panels.find('.' + ctx + ' img').length;
return false;
}
function showArrows(e) {
arrows['fade' + (e.type === 'mouseenter' ? 'In' : 'Out')]();
}
function getPrev() {
currentIndex = currentIndex - 1 < 0 ? currentSize - 1 : currentIndex - 1;
return currentIndex;
}
function doPrev() {
var ctx = panels.find('div.current img');
ctx.removeClass(currentClass).removeAttr('style');
ctx.eq(getPrev()).fadeIn().addClass(currentClass);
}
function getNext() {
currentIndex = currentIndex + 1 >= currentSize ? 0 : currentIndex + 1;
return currentIndex;
}
function doNext() {
var ctx = panels.find('div.current img');
ctx.removeClass(currentClass).removeAttr('style');
ctx.eq(getNext()).fadeIn().addClass(currentClass);
}
$(document).ready(function () {
pages = $('.panels-nav a');
panels = $('.panels');
arrows = $('.arrows');
pages.click(showPage);
panels.bind('mouseenter mouseleave', showArrows);
arrows.find('.prev').click(doPrev).end().find('.next').click(doNext);
pages.eq(0).click();
});
});
</script>
My questions is, how do I change the js file from finding img to finding several different div id's attached to the sliding panles?
Thanks.
any reference to img should be a new selector. Something like 'div.slider', a div with a class slider.
Look at all the finds, thats where you will see the img selectors.

Use JavaScript to alter width of a div

I have some JavaScript code and a button which already has an event/action assigned to it, and I want to add a second event to the button. Currently the relevant bit of code looks like this:
events: {onclick: "showTab('"+n+"')"},
How do I amend this code so that it also increases the 'width' property of a div with class='panel', by a fixed amount e.g. 50px?
EDIT:
I understand. Problem is I don't know how to change id, only classname. The div is constructed in JavaScript using buildDomModel as follows:
this.buildDomModel(this.elements["page_panels"],
{ tag: "div", className: "tab_panel",
id: "tab_panel",
childs: [...]}
)
But the id doesn't get changed to 'tab_panel'. HOWEVER, classname does get changed to 'tab_panel' which is why i tried to use getelementbyclass. So the div has no id and I don't know how to create one using the buildDomModel but I can give unique class. I have put the code in original post too.
This:
events: {onclick: "showTab('"+n+"'); $('div.panel').width('50px');"},
Or you might want to add below line to showTab function.
$('div.panel').width('50px');
Update:
Or you can do with vanilla javascript:
function setWidth()
{
// since you are using a class panel, means more than one div, using loop
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'panel')
{
// set the width now
divs[i].setAttribute('width', '50px');
}
}
}
Or if you want to apply the width to just one specific div, give that div an id and use this function instead:
function setWidth()
{
var div = document.getElementById('div_id');
div.setAttribute('width', '50px');
}
And later use it like this:
events: {onclick: "showTab('"+n+"'); setWidth();"},
Or you might want to add below line to showTab function.
setWidth();
Update 2:
Ok modify the function like this:
function setWidth()
{
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel')
{
// get previous width
var prevWidth = getComputedWidth(divs[i]);
// set the width now
divs[i].setAttribute('width', (prevWidth + 50));
}
}
}
function getComputedWidth(theElt){
if(is_ie){
tmphght = document.getElementById(theElt).offsetWidth;
}
else{
docObj = document.getElementById(theElt);
var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("width");
tmphght = tmphght1.split('px');
tmphght = tmphght[0];
}
return tmphght;
}
Note that with jQuery it should be this code in all:
function setWidth(){
jQuery('.tab_panel').each(function(){
jQuery(this).attr('style', 'width:' + (jQuery(this).width() + 50));
});
}
instead of the function you can use this line of JQuery code:
$('div.tab_panel').attr('style',"width:100px");
any way if you dont want it to be JQuery then this function should work :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel') {
// set the style now
divs[i].setAttribute('style', 'width:100px');
}
}
}
putting width attribute to div wouldnt work, you need to set its style,
so i expect any of the code i provided to work.
oh no the one i sent early just set width to a new value
this one should fix your problem :
var x = $('div.tab_panel')[0].style.width.replace("px", "");
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
ok here is a non JQuery Version :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].style.width.replace("px", "");
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
ok here it is :
JQuery:
function Button1_onclick() {
var x = $('div.tab_panel')[0].clientWidth;
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
}
non JQuert:
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].offsetWidth;
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
}
this should work

Categories

Resources