jQuery accessing listview->ul->li->span->img - javascript

This is my shortcode of li.
<li>
<a href='#'><img src='img.png'/>
<h2 style='margin-top: 0px; padding-top: 0px'>test</h2>
<p><strong>{</strong><label>test</label><strong>}</strong></p>
<p><strong>test</strong></p>
<p><strong style='font-size: 17px; color: #fff'>10</strong>
<br/><span id='onoff'><img src='on.png'/></span>
<span id='delete'><img src='abc.png'/></span></p>
</a>
</li>
As you can see, the li contains to the whole html an <a href>, which will trigger a file when clicked. That said, I would like to detect the click of the images inside the span, both of them separately, <span id='onoff'> and <span id='delete'>
This is what I've tried so far without any result.
$('#page-main-listview ul li span').on("click", function(){
if(($this).attr("id") == 'onoff'){
// I dont know what to put here
// I need to find img now and trigger 'onClick()'
}
});
Edit: I think i've solved the issue, this way:
$('#page-main-listview').delegate('img', 'click', function(){
$atrr = $(this).attr("name");
alert($atrr);
if($atrr == 'on'){
}
});

You are using span IDs instead of classes within a list which leads me to believe you will have problems when adding more list elements.
To make things easier, <span data-tag="onoff" class="clickMe"> for the first image link and <span data-tag="delete" class="clickMe"> for the second. Then you can easily loop through with something like:
$('.clickMe').click(function() {
alert($(this).data('tag'));
});

Related

How i can show the href of all my <a> links inside a span beisde the <a>

I have the following markup, which represents a table which have <a> inside its <td>:-
now i am trying to find a way using javascript, to show the href of all the <a class="ms-listlink"> beside them.so the <td> will contain something as follow:-
Design Transfer
http://***/buisnessfunctions/pmo/progammes/136/
instead of just showing the text:-
Design Transfer
so is there a way to achieve this?
You can do this without javascript - css has a content property that can access attributes. Here's an example:
a {
display: block;
}
a:after {
display: inline-block;
margin-left: 1em;
content: attr(href);
}
Google
Zombocom
Loop through each link, read its href property and insertAfter the link.
$('.ms-listlink').each(function(){
var link = $(this).attr('href');
$(this).insertAfter('<span>'+ link +'</span>');
});
I prefer the CSS solution above, but here's the JS solution FWIW
$('.ms-listlink').each(function() {
const href = $(this).attr('href');
const $td = $(this).closest('td');
$($td).append(href);
})
I really like the CSS answer. Tiny, easy, concise. Just in case you are curious (or for some reason require a JS-only solution), here is a way to do it in plain vanilla JavaScript (no additional libraries):
<div id=container>
<a href=https://google.com >GOOGLE </a> <span></span> <br />
<a href=https://faceboook.com >FACEBOOK </a> <span></span> <br />
<a href=https://yahoo.com >YAHOO </a> <span></span> <br />
</div>
<script>
var container = document.getElementById('container');
var anchor = container.getElementsByTagName('a');
var span = container.getElementsByTagName('span');
for(var item in anchor) {
span[item].innerHTML = anchor[item].href;
}
</script>
*NOTE: If you need the url's to be a clickable part of the hyperlinks, put the span's inside the 'a' tags.

How to remove previous li on anchor click

I am setting some <li> and anchor tag using jQuery . Now i want to remove the attach li on anchor click.Let me show on code what I am trying to do.And I can't assign any id to these elements as they are generating dynamically.
<ul id="imagess">
<li><img width="60" height="60" src="http://example.com/images/event.png"></li> <img style="float: left; margin-left: -25px;margin-top: 60px;" src="http://example.com/images/delete.png">
<li><img width="60" height="60" src="http://example.com/images/event2.png"></li> <img style="float: left; margin-left: -25px;margin-top: 60px;" src="http://example.com/images/delete.png">
</ul>
I am trying to remove the <li> on deletit() js function call
A solution for your current HTML using event delegation.
$(document).on('click', 'li + a', function(){
$(this).prev().remove();
})
However, your HTML/JS should look more like this to be valid:
$(document).on('click', '#imagess li a', function(){
console.log(this);
$(this).closest('li').remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="imagess">
<li>
<img width="60" height="60" src="http://example.com/images/event.png">
<a href="javascript:void(0);">
<img style="float: left; margin-left: -25px;margin-top: 60px;" src="http://example.com/images/delete.png">
</a>
</li>
<li>
<img width="60" height="60" src="http://example.com/images/event2.png">
<a href="javascript:void(0);">
<img style="float: left; margin-left: -25px;margin-top: 60px;" src="http://example.com/images/delete.png">
</a>
</li>
</ul>
$('ul a').click(function() {
$(this).prev().remove();
});
prev() gets the previous sibling to the a element, which is the li. remove() is pretty self explanatory.
Also, your HTML is invalid. The only elements allowed as direct children of ul are li elements.
Edit: The answers with "closest" given above will be correct if you move the a inside the li. People are assuming they're already in there as the HTML is invalid otherwise.
Update : remove inline onclick attribute from a tag as you have defined click event in code itself
Previous fiddle : http://jsfiddle.net/Lp88exqb/
New Fiddle : http://jsfiddle.net/Lp88exqb/1/
You should not have a tag as direct child of ul tag, it should be in li tag and than you have to use following code to remove previous li on any click
$('ul a').click(function() {
$(this).parent().prev().remove();
});
1. Step 1
Your HTML CODE has to be like this
-------------------------------------
<code>
<ul id="imagess">
<li>Img1</li>
Img1
<li>Img2</li>
Img2
</ul>
</code>
-------------------------------------------
2. Write a JS Funcion like this
-------------------------------------------
function deleteit(obj){
$(obj).prev('li').remove();
}
You have the jQuery tag, so here is an example with that:
$(this).closest('li').prev().remove();
Update: from the wording of question details and your comment, it sounds like path is the anchor itself, and that you don't want to remove previous li, but the container li itself, if so, change to:
$(path).closest('li').remove();
Update 2
Check this:
$('#imagess').on('click', 'a', function() {
$(this).prev('li').remove();
return false;
})
However, this is only for your invalid HTML, where the <a> lives directly inside <ul>. In correct way, the <a> should be inside the <li>, which I see is now fixed in another answer.

Replace <img> with <object>

Here is a little challenge: I'm trying to replace all three <img ...> tags in the code below completely by another tag named <object ...>. I Tried with jQuery .replaceWith() but didn't get it.
$( document ).ready(function() {
$("div.gallery_content > div > ul > li:firstchild > img").replaceWith( "<object>...</object>" );
});
I can't change any of the classes or add any ID or class names. And I can't change the code in any way. I can just add some Javascript / jQuery in an .js file that is already attached.
What makes things even more difficult is the fact, that I have to add the Javascript to every page on the website, but the replacement should only take place on a subpage called «spots» (e.g. .com/cms/anything/spots).
This is the code:
<div class="gallery_content">
<div id="navkeys" style="visibility: hidden;"></div>
<div>
<ul style="width: 2281px; margin-left: 0px;">
<li style="margin-left: 0px;">
<img src="XYZ" width="760" height="505" alt="XYZ" style="visibility: visible;">
<div class="gallery_details">
Some Text
</div>
</li>
<li>
<img src="XYZ" width="760" height="505" alt="XYZ" style="visibility: visible;">
<div class="gallery_details">
Some Text
</div>
</li>
<li>
<img src="XYZ" width="760" height="505" alt="XYZ" style="visibility: visible;">
<div class="gallery_details">
Some Text
</div>
</li>
</ul>
</div>
</div>
Has anyone got a clue?
Once a dom element is created, the tag is immutable.
You would have to remove the image element and replace it with an object. So you would need to get all of the information you need and then add an object element.
So you could do something like this:
$("div.gallery_content > div > ul > li:firstchild > img").each(function() {
var src = $(this).attr('src');
var width = $(this).attr('width');
.
.
.
etc...
$(this).remove();
$('<object>...</object>').prependTo('li') //or whatever your selector is to prepend.
});
The other users have given the code for the replacement, but forgot to explain how the code must act to execute only in the target page
var targetPath = "com/cms/anything/spots";
$(window).load(function(){
currentPath = window.location.pathname;
//Checks if the current page coincides with the target page
if(currentPath.indexOf(targetPath)+targetPath.length === currentPath.length){
functionThatReplaces();
}
});
With this, the script will check if the page is the correct before executing the code.
You can create a new object element, with all the attributes of the old one and then replace the img tag.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/z9u5dxgu/2/
$(document).ready(function () {
$("div.gallery_content > div > ul > li > img").each(function () {
// create a new object
var $object = $('<object>');
$object.html($(this).html());
// copy all the attributes
var attributes = $(this).prop("attributes");
// loop through attributes and apply them to object
$.each(attributes, function () {
$object.attr(this.name, this.value);
});
$(this).replaceWith($object);
});
});
If it were not an img you would also copy the innerHTML using .html().
The end result of the JSFiddle looks like:
<li style="margin-left: 0px;">
<object src="XYZ" width="760" height="505" alt="XYZ" style="visibility: visible;"></object>
<div class="gallery_details">Some Text</div>
</li>
The other minor detail you mentioned was matching a specific page only (difficult to test in a JSFiddle):
$(document).ready(function () {
if (window.location.href.indexOf("/cms/anything/spots") > 0){
$("div.gallery_content > div > ul > li > img").each(function () {
// create a new object
var $object = $('<object>');
$object.html($(this).html());
// copy all the attributes
var attributes = $(this).prop("attributes");
// loop through attributes and apply them to object
$.each(attributes, function () {
$object.attr(this.name, this.value);
});
$(this).replaceWith($object);
});
}
});

How to add click event to an element with JQuery which is created by serverside

I create an ul list in serverside as you can see the below. I want to add click event to a elements with jquery but I can't access any elements. Here my codes:
Server side:
StringBuilder sbSubCitchens = new StringBuilder();
sbSubCitchens.Append(#"<div id=""content_1"" class=""subCats"">");
sbSubCitchens.Append("<ul>");
foreach (kitchen kitchen in kitchenList)
{
sbSubCitchens.Append(#"<li><a class="" " + kitchen.KitchenId + #""">" + kitchen.Name + "</a> </li>");
}
sbSubCitchens.Append("</ul>");
sbSubCitchens.Append("</div>");
ltrKitchenList.Text = sbSubCitchens.ToString();
Javascript:
$(document).ready(function () {
$(".mCSB_container ul li a").click(function () {
// do smth...
});
})
Html output :
<div class="mCSB_container" style="position: relative; top: 0px;">
<ul>
<li><a class=" 1">Cafe</a> </li>
<li><a class=" 2">Dünya Mutfağı</a> </li>
</ul>
</div>
Try this:
$(".mCSB_container ul li a").click(function (e) {
e.preventDefault();
// do smth...
});
I think the click may be working, but since you aren't preventing the default action, the link may be reloading the page.
Also make sure the html output is what you expect, since the server-side code you posted, by itself, won't give you the output you posted (and therefore the selector wouldn't work).
I think you have to put the "href" parameter:
Some stuff

Javascript creating <div> on the fly

I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>

Categories