nth-child increase decrease with click - javascript

I have a set of li elements forming a menu. When the user clicks a particular li element I want to change the source of an iframe element to the URL that corresponds to the clicked item.
I've tried the function below but it didn't work. Can somebody please advise how to do this?
http://jsfiddle.net/ZnMTK/8/
$(document).ready(function(){
var source1="http://www.hurriyet.com.tr";
var source2="http://www.milliyet.com.tr";
var source3="http://www.vatan.com.tr";
var source4="http://www.ensonhaber.com";
$("#menubar ul li:nth-child(i)").click(function(){
$(this).attr('src', source(i) );
});
});

You can use an array and then use the clicked li elements index to fetch the target source from array.
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
$("#menubar li").click(function(){
$('#iframe1').attr('src', sources[$(this).index()])
});
});
Demo: Fiddle

This type of functionality is what arrays are for:
$(document).ready(function(){
var sources =["http://www.hurriyet.com.tr","http://www.milliyet.com.tr","http://www.vatan.com.tr","http://www.ensonhaber.com"],
i = 0;
$("#menubar li").click(function(){
$("#iframe1").attr('src', sources[$(this).index()] );
});
});
However, specifying all of your URLs in your JavaScript and relying on the indices matching up with the order of the menu li elements is kind of fragile. I would recommend linking the values more closely, perhaps something like this:
<ul id="menubar">
<li data-src="http://www.hurriyet.com.tr">Hurriyet</li>
<li data-src="http://www.milliyet.com.tr">Milliyet</li>
<li data-src="http://www.vatan.com.tr">Vatan</li>
<li data-src="http://www.ensonhaber.com">Ensonhaber</li>
</ul>
And then with JS:
$(document).ready(function () {
$("#menubar li").click(function () {
$("#iframe1").attr('src', $(this).attr("data-src"));
});
});

Related

Checking list item hover states to trigger an action - jQuery

I have 4 images in an unordered list. Ideally I want to be able to load all the list items into an array and do a check to see which one is currently hovered.
I know using the jQuery is() function I can check which is in an :hover state. How would I apply this check to all items within that list array?
<ul class="image-list">
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
<li class="image-item"><img src="/image1.jpg"/></li>
</ul>
Thanks for any help.
DIM3NSION
Use the mouseover() function:
// Add mouseover event to all your image-items
$('.image-list > .image-item').mouseover(function() {
// $(this) is your hovered image-item object
alert($(this).find('img').attr('src'));
});
Working jsfiddle
Demo: http://jsfiddle.net/GCu2D/758/
JS:
$(function () {
var li = $("ul li"); //get all li. All li are stored in an array.
$(document).on("mouseover", "ul li.image-item", function (e) {
var ele = $(this); //get currently hovered li.
var item = li.index(ele); //get the index of the currently hovered li in that array
console.log(item); //this logs the index. Using this index, do whatever you want with that item.
});
});

Changing the background color of a link after being clicked

I'd like to ask how to change the background color of each link (the rectangular shape surrounding it) to one different color after a link is clicked, and the other links still remain in its original background color.
Each link corresponds to one div placed in the same html file (that I didn't include here).
The point is to let the viewers know which link they are at. By the way, if it is okay I'm looking for the fastest code possible ^_^ (pure css, javascript or jQuery). Appreciate all suggestions!
the highlight only applied to the current link only! (the others will have the normal colors)
<div id="Navigation">
<div id="nav_link">
<ul id="MenuBar" class="MenuBarHorizontal">
<li><a class="MenuBarItemSubmenu" href="javascript:showonlyone('Index_frame');" >Home</a>
<ul>
<li><a href="javascript:showonlyone('Specification_frame');" >Specification</a></li>
<li><a href="javascript:showonlyone('Images_frame');" >Images</a></li>
<li>Video</li>
<li>Contact</li>
</ul>
</li>
<li><a href="javascript:showonlyone('Specification_frame');" >Specification</a></li>
<li><a href="javascript:showonlyone('Images_frame');" >Images</a></li>
<li>Video</li>
<li>Contact</li>
</ul>
</div>
<!--End of nav_link-->
</div>
<!-- End of Navigation-->
function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(1000).fadeIn(500);
}
else {
$(this).hide(1500).fadeOut(500);
}
});
}
EDITED
Guys, there is this one thing that I'm still stuck at even though I spent time on it a lot, I added some more JavaScript links the same with the above in the page with the idea that these new links will be functional just like the former. That is being clicked on ==> the highlight will appear only on these Navigation links. I tried to modify the function from jjurm like this
$(function(){
$("#MenuBar a,#colOne a").bind("click", function(){
var names=$(this).attr('name');
$("#MenuBar a").removeClass("clicked");
$("#MenuBar a[name='names']").addClass("clicked");
});
});
It didn't work and neither did the old ones that used to work
In a similar question to yours I once found out that only changes in text color are allowed some properties can be changed if you use a:visited pseudo-class (UPD: and background-color is one of them). But since your links are javascript links, the :visited selector will not work, hence you cannot do it as a pure CSS solution. You will have to use some kind of javascript. If jQuery is ok, you can try this:
$('a').on('click', function(){$(this).css("background-color","yellow");});
Perhaps you can change the "showonlyone" function? Then you could add the background changing code to it.
You can do this by simple css code:
#MenuBar a:visited {
background: yellow;
}
Edit:
As far as this doesn't work with javascript links (but I haven't tried it), there is other solution with jQuery and CSS.
jQuery code:
$(function(){
$("#MenuBar a").bind("click", function(){
$(this).addClass("clicked");
});
});
CSS:
#MenuBar a.clicked {
background: yellow;
}
Edit2:
Ok, if you want to keep highlighted only last clicked element, it's enough to add this simple line to javascript code:
$(function(){
$("#MenuBar a").bind("click", function(){
$("#MenuBar a").removeClass("clicked"); // Remove all highlights
$(this).addClass("clicked"); // Add the class only for actually clicked element
});
});
Edit3:
If you want to have more links that point to same location and to highlight all of them if one is clicked, follow this:
$(function(){
// Assume that your 'a' elements are in #MenuBar and #colOne
$("#MenuBar a, #colOne a").bind("click", function(){
// Remove all highlights
$("#MenuBar a, #colOne a").removeClass("clicked");
// Store the name attribute
var name = $(this).attr("name");
// Find all elements with given name and highlight them
$("#MenuBar a[name='"+name+"'], #colOne a[name='"+name+"']").addClass("clicked");
});
});
You can add an active class to the clicked anchor. Using live NodeList should work really fast as you also need to unselect previously selected item:
var a = document.getElementById('Navigation').getElementsByClassName('active');
$('#Navigation').on('click', 'a', function() {
if (a[0]) a[0].className = '';
this.className = 'active';
});
http://jsfiddle.net/vBUCJ/
Note: getElementsByClassName is IE9+ if you need to support older versions use jQuery:
var $a = $('#Navigation a');
$('#Navigation').on('click', 'a', function() {
$a.removeClass('active');
$(this).addClass('active');
});
http://jsfiddle.net/vBUCJ/1/
$('#MenuBar').on('click', 'a', function() {
$(this).css('background-color', '#bada55');
});
or if you need unique colors you can use the data-attribute.
$('#MenuBar').on('click', 'a', function() {
var $elem = $(this);
$elem.css('background-color', $elem.data('color'));
});
I'd recommended adding classes instead and using css to define styles.
$('#MenuBar').on('click', 'a', function() {
$(this).addClass('clicked-menu-link');
});
edit:
To remove the other clicks use:
$('#MenuBar').on('click', 'a', function() {
var fancyClass = 'clicked-menu-link';
$('#MenuBar a').removeClass(fancyClass).filter(this).addClass(fancyClass);
});

Jquery add selected class to li

Hi i have following ul li that display categories name:
<ul>
<li class="selected" data-tab-id="0"></li>
<li data-tab-id="12">...</li>
<li data-tab-id="3">...</li>
<li data-tab-id="15">...</li>
<li data-tab-id="7">...</li>
</ul>
The javascript scripts as follow:
<script type="text/javascript">
var cat_id = '<?=$this->catid?>'
$(document).ready(function () {
});
</script>
Currently the page at index so first li data-tab-id="0" will be selected class also var cat_id will be return nothing. Now when user navigate to another tab such as data-tab-id="12", var cat_id will be return value of 12, how can i remove class selected from default li and replace it to data-tab-id="12". Thanks
Assuming list as ID of the UL – just to avoid problem in case you have multiple UL around the page:
$("ul#list")
.find(".selected").removeClass("selected")
.end()
.find("[data-tab-id=" + cat_id + "]").addClass("selected");
You can also do that in two jQuery calls, of course:
$("ul#list .selected").removeClass("selected");
$("ul#list [data-tab-id=" + cat_id + "]").addClass("selected");
use addClass() and removeClass() to add and remove class respectively.
try this
updated
var cat_id = '<?=$this->catid?>';
$('li').removeClass('selected');
$('li').each(function(){
if($(this).attr('data-tab-id')==cat_id){
$(this).addClass('selected');
}
})
updated without using loop..
var cat_id = '<?=$this->catid?>';
$('li').removeClass('selected');
$('li[data-tab-id='+cat_id+']').addClass('selected');
fiddle here
updated fiddle
use this sample
$('ul li').click(function() {
$('ul li.selected').removeClass('selected');
$(this).closest('li').addClass('selected');
})

Jquery get number of nested elements

Consider a dynamic dropdown-menu. Because of creating this code server side I don't know the exact number of li situated in div 'sub'.Example HTML output:
<li>
Videos
<div id="sub">
<ul>
<li>Main</li>
<li>Acting</li>
<li>Animals</li>
</ul>
</div>
</li>
The following script should give the number of li in the in div id="sub"
$(function() {
$('.tabMenu li a').click(function() {
currentLink = $(this);
//Get number of children elements
alert(currentLink.children().size());
});
Any help will be greatly appreciated.
alert(currentLink.parent().find('li').size());
First: where is your .tabMenu in your code?
Try with:
.length;
Working solution
$('.tabMenu li a').click(function() {
currentLink = $(this);
alert(currentLink.parents('ul').children('li').length);
});
What you need to do is get the parent container of the li element, then see how many children it has:
$(function() {
$('.tabMenu li a').click(function() {
// Get the parent ul of the current link
var currentLinkParent = $(this).parents("ul:first");
alert(currentLinkParent.children().size() );
});

Need clean jQuery to change parent's class when children are clicked

I needed some method of adding/removing classes of a parent element when it's children are clicked to reflect which child is currently selected. In this case a UL parent and LI children in a tab scheme. I needed a way to mark the current tab on the UL so I could style a background sprite on the UL; since styling my LI's backgrounds would not work with the graphics in this case.
I am a jQuery/Javascript/DOM novice, but was able to piece together an ugly solution for starters,
HTML
<!-- tabs -->
<ul class="tabs currenttab-info">
<li id="tab-info" class="info"><strong>Information</strong></li>
<li id="tab-write" class="write"><strong>Write Feedback</strong></li>
<li id="tab-read" class="read"><strong>Read Feedback</strong></li>
</ul>
Javascript
// send '.currenttab-x' to '.tabs' and remove '.currenttab-y' + '.currenttab-z'
// when LI #tab-X is clicked ...
$( '#tab-info' ).click(function() {
// ... find the UL and remove the first possible conflicting class
$('.tabs').removeClass("currenttab-read");
// ... find the UL and remove the other possible conflicting class
$('.tabs').removeClass("currenttab-write");
// ... find the UL and add the class for this LI
$('.tabs').addClass("currenttab-info");
});
// ... repeat ...
$( '#tab-write' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-read");
$('.tabs').addClass("currenttab-write");
});
$( '#tab-read' ).click(function() {
$('.tabs').removeClass("currenttab-info");
$('.tabs').removeClass("currenttab-write");
$('.tabs').addClass("currenttab-read");
});
This actually seems to be working, BUT it's a fumbling solution and I am sure there is a better way. Some of you jQuery ninjas will know how to put this functionality together really elegantly, any help?
Also I would like to add onto this so that the clicked LI is also given a class to show it is selected while the other LIs are stripped of any such class. The same sort of thing I already am doing for the UL; I can see how to do that with my awkward approach, but it will mean even more and more lines of messy code. If your improvement also included a way to do change classes of the LIs I'd appreciate it
FYI: I'm using jQuery Tools Tabs with this so there is more jQuery then I showed, but only the bit I quoted seems relevant.
html
I will remove ids of li if you are not using it for other purposes.
<ul class="tabs currenttab-info">
<li class="info"><strong>Information</strong></li>
<li class="write"><strong>Write Feedback</strong></li>
<li class="read"><strong>Read Feedback</strong></li>
</ul>
jQuery
$('.tabs li').click(function() {
var $li = $(this);
$li.addClass('current').siblings().removeClass('current'); // adds a current class to the clicked li
var $ul = $li.parent();
$ul.removeClass("currenttab-info currenttab-read currenttab-write")
.addClass("currenttab-" + this.class ); // assuming li only holds one class e.g. class="write"
});
You can just do something like this:
$('.tabs > li').click(function() {
$(this).parent().attr('class', 'tabs').addClass('currenttab-'+$(this).attr('class'));
});
$("UL.tabs LI A").bind('click',function(e){ //bind a Click-Event handler to the Links
var $target = $(e.target); //the jQuery-Object-Reference to the clicked target ( $(this) should work too)
var LIClasses = $target.parents('LI').attr('class'); //A list of all Classes the parrent LI of the clicked Link have
$target
.parents('UL.tabs')
//now you can remove and add classes to the parent "UL.tabs"
.removeClass('...')
.addClass('...')
.end() //after .end() the chain for .parents-match is broken
.parents('LI')
//here you can add and remove classes from the parent LI
.removeClass('...')
.addClass('...')
.end() //after .end() the chain for .parents-match is broken
;
});
Notes:
jQuery is chainable.
.removeClass() and .addClass() can work with multiple classnames at the same time by speration with a space (like .removeClass('class1 class2'))
The full solution:
var relevantClasses = ['read','write','info'];
$("UL.tabs LI A").bind('click',function(e){
var $target = $(e.target);
var relevantClass = '';
for( var cl in $target.parents('LI').attr('class').split(' ') )
if( jQuery.inArray(relevantClasses , cl) > -1 ){
relevantClass = cl;
break;
}
$target
.parents('UL.tabs')
.removeClass(jQuery.map(relevantClasses , function (className) { return 'currenttab-' + className; }).join(' '))
.addClass('currenttab-'+relevantClass )
.end()
;
});
First of all you can chain the method calls...
$('.tabs').removeClass("currenttab-read currenttab-write").addClass("currenttab-write");
This would make the code much cleaner...
EDIT: I'll try such things in Fiddle http://jsfiddle.net/JvtAz/

Categories

Resources