Unable to detect what div is clicked - javascript

I want every li tag to show the a's clicked href content below that li tag in a div. For example, I have a structure like this:
<ul id="ids">
<li class="res"><a class="item">item1</a></li>
<li class="res"><a class="item">item2</a></li>
<li class="res"><a class="item">item3</a></li>
</ul>
Dynamically if a's href is clicked, accordingly a function that shows the div <div class="testing"><h3>showing item1 here</h3></div> outside the <a> tag needs to be shown. That function could take time so until then Loading... needs to be shown. But I am unable to detect where the user has clicked as class names are the same. Once loading is done, loading should be hidden.
So far I have this:
$(document).on('click', '.item', function(e) {
e.preventDefault();
$(this).append('Loading');
//function code here
$(this).append('<div class="testing"><h3>showing item1 here</h3></div>');
});
Also, the function appends 1 div tag with class 'mydiv', that needs to be hidden. But again, since class names that get appended to every <li> is the same, I don't know where the click has taken place to detect it.
to summarise:
show a list of elements which has anchor tag
click on every element should show the content of the click in a div under that anchor tag
content of anchor tag can take 2 seconds so until then user should see "loading". Once it loads, loading should be hidden

You are looking for $.after() or $.insertAfter():
$(document).on('click', '.item', function(e) {
e.preventDefault();
var aTag = $(this);
if (aTag.siblings('.testing, .loader').length === 0) { //it's not loaded or loading
var loader = $('<div class="loader">Loading</div>');
loader.insertAfter(aTag);
//function code here
loader.remove();
aTag.after('<div class="testing"><h3>showing ' + aTag.html() + ' here</h3></div>');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ids">
<li class="res"><a class="item">item1</a>
</li>
<li class="res"><a class="item">item2</a>
</li>
<li class="res"><a class="item">item3</a>
</li>
</ul>
If you want to avoid multiple loadings check if it exists before:
if(aTag.siblings('.testing, .loader').length === 0){ //it's not loaded or loading
}

You can get the href attribute using `$(this). This should work.
$(document).on('click', '.item', function(e) {
e.preventDefault();
var href = $(this).attr("href");
$(this).append('Loading');
$(this).append('<div class="testing"><h3>showing ' + href + ' here</h3></div>');
});
Also, the code above will append the div inside the a tag. You probably want to put it somewhere else using something like
$("#messageDiv").html('<div class="testing"><h3>showing ' + href + ' here</h3></div>');
To hide the loading message, you can wrap that in a span
$(this).append('<span class="loadingspan">Loading</span>');
Then in the code that runs when the load is complete, you can use
$('.loadingspan').hide();

Related

How to refresh a DIV with random different names?

I´m doing like this. Works fine with just one div with a static name.
Problem is when i want to refresh DIV´s with other names like myDiv1, myDiv2 etc.
I have tried javascript by sending ID to the funciton, my webpage jumps up to the begining, I dont want that to happen. That doesn't happen with the code below.
$(function() {
$("#refresh").click(function(evt) {
$("#myDiv").load("update.php")
evt.preventDefault();
})
})
<div id = 'myDiv" . $row["id"]. "' ><a href='#' id='refresh'> Click Here </a></div>
This Would also work, but then I have to generate one jquery-function for every DIV
$(function() {
$("#refresh1").click(function(evt) {
$("#myDiv1").load("update.php")
evt.preventDefault();
})
})
<div id = "myDiv1" ><a href='#' id='refresh1'> Click Here 1 </a></div>
$(function() {
$("#refresh2").click(function(evt) {
$("#myDiv2").load("update.php")
evt.preventDefault();
})
})
<div id = "myDiv2" ><a href='#' id='refresh2'> Click Here 2 </a></div>
You can access the parent element in the click event and execute the load on it like this:
$(this).parent().load("update.php");
If you don't want a redirection to happen, I would suggest that you don't use a link. Maybe a button or a span
You may selects elements by beginning part of your id:
$('div[id ^= "myDiv"]')

On load page is going to first tab

I have created one page where that page contained the menu bar as tabs.
My url is mydomain.com/UI/ID=2?#about
Where with respective # the other tabs are there like photo,comment and setting.
When i reload any other tab like mydomain.com/UI/ID=2?#comment it going to about tab fraction of seconds then again it will come back to respect comment section.
Here is my code
<script type="text/javascript">
$(document).ready(function() {
$(".menu_content").hide();
var tabvalue=document.location.hash;
var activetab=$(this).find("a").attr("href")
$(".menu_content"+tabvalue).show();
//$(".menu_content:first").show();
$("ul.menu li:first").addClass("active");
$("ul.menu li").click(function() {
var activeTab = $(this).attr("rel");
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".menu_content").hide();
$("#"+activeTab).fadeIn();
});
var firstLi = $("ul.menu li:first").attr('rel');
if('#' + firstLi !== tabvalue) {
$("ul.menu li:first").removeClass('active');
$('li[rel="'+tabvalue.substring(1)+'"]').addClass('active');
}
});
</script>
where menu_content is class name for all tabs.
Can any one guide me how to resolve this problem.
It sounds like you're running this code after the entire page has loaded therefore you're getting a flash while the HTML is rendered in it's default state, and then to the changed version once the code executes.
The nicest way to do this would be to not use a hash for this, rather have the page in the URL i.e. mydomain.com/UI/?ID=2&page=about and use server side code to render it correctly first time, and then update the url using history.pushState in JavaScript.
But if this is all a JavaScript based page, then I would say the easiest way would be to have all of the tabs 'inactive' by default, and then only add the 'active' class when you load the page (either to the hash value, or 'about' by default).
Example:
Style
<style type="text/css">
.menu_content .panel {
display:none;
}
</style>
Script
<script type="text/javascript">
$(document).ready(function() {
//if there's a hash, get it but remove the hash, or use 'about' as a default
var selectedTab = document.location.hash ? document.location.hash.replace("#", "") : "about";
$("li#" + selectedTab).addClass("active");
$("#" + selectedTab + "_panel").show();
$("ul.menu li").on('click', function() {
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".panel").hide();
$("#" + $(this).attr("id") + "_panel").show();
});
});
</script>
HTML
<ul class="menu">
<li id="about">About</li>
<li id="comment">Comment</li>
<li id="contact">Contact</li>
</ul>
<div class="menu_content">
<div id="about_panel" class="panel"></div>
<div id="comment_panel" class="panel"></div>
<div id="contact_panel" class="panel"></div>
</div>

How to change image with onclick while a list is using slideup and slidedown

I would like to change the src of an img when the parent of listed children is clicked. I am using some code I have been working with that I found on StackOverflow because I was having problems with slideup and slidedown.
Next to each uppermost item (parent), to the left will be an arrow icon pointing to the right. Upon clicking the icon, this image should change to an arrow pointing down.
I can get the image to change onClick, but unless you click on the image, the image does not change back. Therefore, I believe I need the change to be pegged to the slideup and slide down functions. The image should also change back if you click on the close link or when clicking on a new Parent.
I can live without the 'only one list can be shown at a time' functionality, which would eliminate the need for the image to also change on clicking a new parent.
For this fiddle, I have only applied what I was trying to do to the first parent of the list: http://jsfiddle.net/9aa5n/51/
HTML:
<li><img src="arrowright.png"></li>
<li class="show_hide" id="1C">
<p>lkjlkjasdfasdf</p>
Close
</li>
<li>Edit</li>
<li class="show_hide" id="2C">
<p>lkjlkjasdfasdf</p>
Close
</li>
<li>Edit</li>
<li class="show_hide" id="3C">
<p>lkjlkjasdfasdf</p>
Close
</li>
jQuery / Javascript:
$(document).ready(function() {
$('.show_hide').slideUp(0);
$('.edit_this').click(function() {
$('.show_hide').slideUp(300);
var takeID = $(this).attr('id');
$('#' + takeID + 'C').slideDown(300);
});
$('.close').click(function() {
var takeID = $(this).attr('id').replace('Close', '');
$('#' + takeID + 'C').slideUp(300);
});
});
$('#img-tag').on({
'click': function() {
var src = ($(this).attr('src') === 'arrowright.png')
? 'arrowdown.png'
: 'arrowright.png';
$(this).attr('src', src);
}
});
I updated your jsfiddle: http://jsfiddle.net/9aa5n/53/
Since you didn't provide absolute paths to images, I added some from the net.
I removed your click event, and replaced it with this, I believe your issue was how you were referencing the elements in jQuery.
$(".edit_button").click(function() {
var img = $(this).find("img").first();
console.log(img.attr("src"));
if (img.attr("src") === 'http://iconizer.net/files/Brightmix/orig/monotone_arrow_right.png') {
img.attr("src", 'http://png-3.findicons.com/files/icons/2315/default_icon/256/arrow_down.png');
console.log(img.attr("src"));
} else {
img.attr("src", 'http://iconizer.net/files/Brightmix/orig/monotone_arrow_right.png');
console.log(img.attr("src"));
}
});
This should get you started to finish polishing up the UI,
i.e. closing all .edit_button and then open only the $(this).find("img").first() element ...

How to apply CSS for the menu while selecting?

I have a task to highlight the menu as selected while loading the page. For that I have the following code:
$('.menuHeader').each(function () {
$(this).attr('id', 'menu' + ($(this).index() + 1));
$(this).val($(this).index() + 1);
// Set the dynamic ids for links
$(this).find('a').attr('id', 'link' + ($(this).index() + 1));
//alert('New ID : ' + $(this).find('a').attr('id'));
});
$('.menuHeader a').click(function () {
alert("a");
$('.menuHeader a').removeClass('menuHeaderActive');
$(this).parent().parent(".menuHeader").addClass('menuHeaderActive');
});
But when I select the second menu, it's refreshed and missing the selection.
HTML:
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
How can I solve this problem?
function Home() {
window.location.href = "../../home/welcome";
}
function NewTransaction() {
window.location.href = "../../EnergyCatagory/index";
}
I think you could amend your hyperlinks to include the correct url. Then in you jQuery test the browsers current url against the hyperlinks url - if it's a match apply your menuHeaderActive class.
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('.menuHeader a[href="' + currentUrl + '"]');
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
When the page reloads after one of the menu links have been clicked the script I've shown should run and $('.menuHeader a[href="' + currentUrl + '"]'); should find the menu link (hyperlink/a-tag) that matches the url the user navigated too. Then it's a case of finding the container div and adding your class.
Basically you don't add the css class when the user clicks the menu link; you have to set the css class after the page has redirected to the other page. So it's the other page that has to set the css class against the correct active menu link. There are 100's of ways to do this but based on what you've provided matching urls is the simplest.
Personally I'd have each page register a page id that corresponds to one of the menu links. Something like this...
HTML
Note the attribute data-associated-page-id added to each menuHeader div
<div class="menuBar">
<div class="menuHeader ui-corner-top" data-associated-page-id="home-welcome">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top" data-associated-page-id="energy-catagory-index">
<span>New Transaction</span>
</div>
</div>
Javascript
Added to each page
document ready handler for welcome page aka ../../home/welcome
$(document).ready(function () {
SetActiveMenuCssClass('home-welcome');
});
document ready handler for energy catagory index page aka ../../EnergyCatagory/index
$(document).ready(function () {
SetActiveMenuCssClass('energy-catagory-index');
});
function defined globally
function SetActiveMenuCssClass(pageId) {
// finds div with menuHeader class that has the attribute data-associated-page-id equal to the page id
// then sets the active class
$('.menuHeader[data-associated-page-id="' + pageId + '"]')
.addClass('menuHeaderActive');
}
If you were using a server side language like PHP then you could do something like this https://stackoverflow.com/a/11814284/81053
NOTE: The answer Chris provided works really well, but you have to actually have the link in the href of <a></a>, otherwise it will be undefined.
You could add an id to a with the link and then use
var menuLink = $('#'+currentUrl);
the code provided by Chris
(this way the page won't redirect because you clicked the link but will run the function instead)
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
And the JS
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('#'+currentUrl);
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
On a side note, if that's a different page you only have to add menuHeaderActive to the active a and remove it from the other on that specific page

Jquery navigation menu

The above code does not work properly. I need to implement a simple menu with sub-menu items using Jquery. When I open the web-page, I see the content of all menus and submenus all together (like a stack). I need to improve JavaScript shown below in order to properly assign the content to menu items. So, when I click "menu2",there should be the content of DIV id = "menu2". Now I see all content on one page.
<!-- Start css3menu.com BODY section -->
<ul id="css3menu1">
<li class="topfirst"><a class="pressed" href="#menu1" style="height:40px;line-height:40px;"><span>menu1</span></a>
<ul class = "menu">
<li>submenu11</li>
<li>submenu12</li>
<li>submenu13</li>
<li>submenu14</li>
</ul></li>
<li class="menu">menu2</li>
<li class="menu">menu3</li>
<li class="toplast">menu4</li>
</ul>
<!-- End css3menu.com BODY section -->
<script>
$('ul.menu').each(function() {
var $active, $content, $links = $(this).find('a');
$active = $links.first().addClass('active');
$content = $($active.attr('href'));
$links.not(':first').each(function() {
$($(this).attr('href')).hide();
});
$(this).on('click', 'a', function(e) {
$active.removeClass('active');
$content.hide();
$active = $(this);
$content = $($(this).attr('href'));
$active.addClass('active');
$content.show();
e.preventDefault();
});
});
</script>
This line has an issue
$content = $($active.attr('href'));
There is no item with that ID... ($content is length 0)
e.g.
you press a link with href="#menu1"
$active.attr('href') equals to #menu1
which translates to $content = $("#menu1");
there is no element on the page with ID "menu1"
In jQuery a selector with a hash (#) means - find an element with the id after the hash sign
So #menu1 means the same (almost) as document.getElementById("menu1")
However there is no element with that ID (or any id that is equal to the href values)
It might not be the last issue, but this is the next stop in the attempt to make it work...
See in jsFiddle

Categories