How to copy elements into a div after an on click action? - javascript

Using JavaScript and JQuery and underscore
Currently I have the following
<div id="select"></div>
which is populated by the following code
$(document).ready(function () {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function (e) {
$(this).width(100).height(100).appendTo('#select');
So at the moment only the img is taken and placed inside #select, but I would also like for it to include item.A item.C and item.C
But I'm not sure how to change the $(document).ready(function () { code block to achieve this?
I thought I might need to give the div an id and reference that?
I've been able to take the whole lot by concatenating the code block, but thats not how I want it to work, I'd like each element seperate so that I can target it with CSS.
_.each(Badges, function (item) {
var wrapper = $('<div class="wrapper"></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.A + '</div>');
wrapper.append('<div>' + item.B + '</div>');
wrapper.append('<div>' + item.C + '</div>');
$('#container').append(wrapper);
});

You could use jQuerys ".parent()" method to get the parent of the img tag - in this case your wrapper div and add this to your select.
The code could look like so:
$(this).width(100).height(100);
$(this).parent().appendTo('#select');
for shrinking the image and appending the whole wrapper including img and items to your select.
Hope this helps

Related

Jquery: Getting the id of an html element: why one solution works and the other don't

I am referencing one element on an index page hidden initially and then showed with jquery on an index.html page. Can't explain why the first ones doesn't work, even if it should, but the last one does. I am getting the id of a pressed button "id='edit1'...2...3..etc" Thank you!
//why this doesn't work and the next one does???
/*$('.edit-btn').click(function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
$('.edit-btn').on('click', function(){
var id = $(this).attr('id');
console.log("btn1:", id);
});
*/
var id;
$("body").on("click",".edit-btn",function(){
id = (this.id).replace("edit","");
UPDATE:
The containers are hidden and shown using this function:
function hideWindowsAndShowOneWindow(sWindowId) {
$('.wdw').hide(); //fadeout 500
$('#' + sWindowId).show(); // fade in 500
}
So the div container, I am trying to reference by id was hidden after the page was loaded or maybe before the page is loaded. My guess is after the page is loaded...
The HTML:
<div class="wdw" id="wdw-events">
<h4>Events text</h4></br>
<div id="content"></div>
<h4>Edit Events</h4></br>
<div>
</div>
It is added/injected after the page was loaded with this js script, but still what has the last method special, just referencing through the document down to the id attribute of the button:
finalEventsLS.forEach(function (item) {
var date = item.date.day + "/" +item.date.month + "/" + item.date.year;
$('#content').append("<ul><li>" +
"Event nr.: " + item.id + " " +
"Name: " + item.name + " " +
"Topic: "+ item.topic + " " +
"Speaker: "+ item.speaker + " " +
"Date: " + date + " " +
"</li><button class='edit-btn' id='edit" + item.id + "'>Edit</button>
</ul>");
})
It's hard to tell, since you've only shared your jQuery. Update with your HTML please.
If you are referencing an element which was added to the DOM after the initial page load, .click will not work, because it only looks for elements initially loaded into the DOM. Instead, you would use the .on method, which looks for elements added to the DOM both before and after initial load.
UPDATE:
I should have looked closer. The second snippet of code that didn't work, but used the .on method, most likely didn't work because you are still trying to access the .edit-btn element, which at this point I'm assuming was added after page load. The code snippet that does work, is accessing the body element first. I will try to find and update with a better explanation, but the .on method still needs to find a element that existed in the DOM initially. From there, it can climb down the tree to find .edit-btn element.

How can I replace the result of a getelementbyid to show a text link?

I have the code below:
$('a').on('click', function () {
$('#show').html($(this).attr('data-owner') + '<br><img src="' + $(this).attr('data-owner_logo') + '"/><br>' + '<br>' + $(this).attr('data-owner_url'));
I have amended it so that data-owner_logo returns an image in the html div, but how can I amend the code so that the data-owner_url returns a clickable link as specified text (e.g. 'More info') instead of the full url? Any help appreciated, I have tried everything!
Thanks
Maybe html() is not the best function to call here but if you must:
$('a').on('click', function () {
$('#show').html(... + '<a href="' + $(this).attr('data-owner_url')
+ '">More info</a>'
);
I prefer to use append(), it's more readable (but slower):
$('#show')
.empty() // clear node
.append(document.createTextNode($(this).attr('data-owner')))
.append($('<br />'))
.append($('<img />').attr('src', $(this).attr('data-owner_logo')))
.append($('<br />'))
.append($('<a />').attr('href', $(this).attr('data-owner_url')).text('More info'))
;

how to remove particular li from ul using javascript/jquery?

HTML string:
var ul = document.getElementById("list");
$("#list").append(
"<li class='margbottom'>" +
"<label id='id_'><img src='images/icon-approved1.png' class='imgspace' align='absmiddle'/><span id='categoriesName'>" + categoryName + "</span>: <span id='categoriesValue'>" + value + "</span></label>" +
"<div class='menuicon'>" +
"<ul>" +
"<li><a href='#url' onclick='removeCategory();'><img src='images/icon_minus.png'></a></li>" +
"<li><a href='#url'><img src='images/icon-searchby-s.png'></a></li>" +
"</ul>" +
"</div>" +
"</li>"
);
JS:
function removeCategory(){
alert("Inside removeCategory");
var elem = document.getElementById('list');
elem.parentNode.removeChild(elem);
}
I have created dynamically li list and I need to remove it dynamically. bt by calling removeCategory it is removing all element instead of particular one.
Anyone can help?
Thanks in Advance.
In this specific situation, you should pass this to the removeCategory function and use it as the element.
So, basically -
<a href='#url' onclick='removeCategory();'
Should be -
<a href='#url' onclick='removeCategory(this);'
And the function should be -
function removeCategory(elem){
alert("Inside removeCategory");
elem.parentNode.removeChild(elem);
}
However, adding HTML within the JavaScript like this is discouraged. If you must, at least do not use inline event listeners, but add them using jQuery instead ($("#list a").on("click", removeCategory); and then just use this within the updated function instead of elem).
Also, your code was indeed removing the entire list, because you are always removing the parent element of the element that has the list ID.
In jQuery you can do like this:
Add class 'removeLink' to your tag. No need for onClick() action.
jQuery code to remove:
$('removeLink').click(function(){
var iconDiv = $(this).closest('.menuicon');
var li = iconDiv.closest('<li>');
li.remove();
});
$("ul").find("[particular li selector]").remove();
The above is just a starting point. It all depends on how easy access you have to the particular li in question. You can either access it directly (by id) or via the parent in some way.
If possible do this
$("#particularLI").remove();

Jquery mouse over adding css

I have a p tag inside an anchor, there many be a variable number of instances of this during the loop. My goal is to on hover make the p tag expand and show more information. I have this so far in terms of mouseover.
however this is not working for me. does anyone have any ideas how to achieve this? someonehow i need to use the passed parameter 'e' to change the height
boxOPToneplustwo : this is an a tag as well.
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(e.target).next('p').addClass("popupHighlight");
});
element creation:
anchorElement = "<a id='anchor" + countWide + "' class=\"boxOPToneplustwo\" alt=\'"+ image_website +"' style=\"cursor:pointer;width:"+ itemWidth + "px"+";height:"+anchorHeight+";position:absolute;left:"+ locationLeft + "px"+";top:0.3%;\" ><p id=\"test\" class=\"popupDynamic\"> " + popupImageTitles[i] + "</p>";
anchorElement += '</a>';
with jQuery you can use this to refer to the handled element.
$('.boxOPToneplustwo').mouseover(function (e) {
console.log("in");
$(this).next('p').addClass("popupHighlight");
});
http://api.jquery.com/mouseover/
Console play
e.g: trying putting the following code in the console (F12) and see what it does to SO :P
$("p, span").mouseover(function(){ $(this).css("display", "none"); } );

jquery html function isn't working

I am tring to show twitter user information on my web page. I have created a div tag which is will contain user information using jquery. I want to show user information when the cursor is over this div tag. Below is my code in jquery:
var hideDelay = 500;
var currentID;
var hideTimer = null;
var container;
$(function () {
container = $('<div id="personPopupContainer" style=\"max-width:400px;\">'
+ '<table border="0" cellspacing="0" cellpadding="0" align="center" class="personPopupPopup">'
+ '<tr>'
+ ' <td class="corner topLeft"><div style="position:absolute;top:15px;left:-16px;"><img src="images/balloon_tail.png" /></div></td>'
+ ' <td class="top"></td>'
+ ' <td class="corner topRight"></td>'
+ '</tr>'
+ '<tr>'
+ ' <td class="left"></td>'
+ ' <td><div id="personPopupContent"></div></td>' //the div tag is here
+ ' <td class="right"></td>'
+ '</tr>'
+ '<tr>'
+ ' <td class="corner bottomLeft"> </td>'
+ ' <td class="bottom"></td>'
+ ' <td class="corner bottomRight"></td>'
+ '</tr>'
+ '</table>'
+ '</div>');
$('body').append(container);
$('#personPopupContainer').mouseover(function () {
if (hideTimer)
clearTimeout(hideTimer);
});
$('#personPopupContainer').mouseout(function () {
if (hideTimer)
clearTimeout(hideTimer);
hideTimer = setTimeout(function () {
container.css('display', 'none');
}, hideDelay);
});
});
That is working well. But the below code that is
$('#personPopupContent').html('<center><img src="images/loading_sm.gif" /></center>');
isn't working.
function UserMouseOver(o) {
var obj = $("#" + o);
var Settings = obj.attr('rel').split(',');
var UserID = Settings[0];
var ScreenName = Settings[1];
if (hideTimer)
clearTimeout(hideTimer);
var pos = obj.offset();
var width = obj.width();
if (pos != null && width != null) {
container.css({
left: (pos.left + width) + 20 + 'px',
top: pos.top - 23 + 'px'
});
}
$('#personPopupContent').html('<center><img src="images/loading_sm.gif" /></center>');
}
what I am doing wrong? Can someone please help me?
Note: in the actual code there is no typo ( the image tag isn't closed early ) but in the code you focus on, there is a typo, as Stian points out.
Longshot.. Is the image even available? You can use this plugin:
https://github.com/desandro/imagesloaded
..then change the HTML once the image is known to be in the DOM.
Your question does not entirely explain what you are trying to do. However, I can at least explain why your image isn't showing.
First, you need to call your function UserMouseOver(o) from inside $('#personPopupContainer').mouseover(function () {. . .}. The way you coded it, UserMouseOver(o) will never get called, and none of the logic in the function will get executed.
Second, in your $('#personPopupContainer').mouseout(function () {. . .}, the line container.css('display', 'none') is hiding your entire container object (ALL your HTML!) on mouseout. That will cause your "loading" gif to never display, because the div you are trying to display (personPopupContent) resides within the container object you just set to display: none! You should set the display to none only on the particular element you are trying to hide; for example, you could add id="balloon_tail" to your balloon image and change the Javascript line to $('#balloon_tail).css('display', 'none').
Third, you will get an error on the line var Settings = obj.attr('rel').split(','); because you did not include a rel attribute in your outermost element personPopupContainer. You will need to add a rel attribute of comma separated strings to this element for this line to work. (However, according to W3C, the only official element that uses the rel attribute is <a>, the anchor tag.)
Finally, I would add an image tag to #personPopupContent to make it something like <div id="personPopupContent"><img src="" id="loading_sm" /></div>. Then you can change
$('#personPopupContent').html('<center><img src="images/loading_sm.gif" /></center>');
to
$('#loading_sm').attr("src", "images/loading_sm.gif");
but that's just me.
I hope this helps!
If the code is working as you stated (I can't see where you are calling your mouse over method) and it's only the image that isnt showing.
Use a Web Debugger to check for any 404 errors e.g. http://www.fiddler2.com/fiddler2/ or even your browser's F12 web debugger.
Make sure your path to the image is correct.
UPDATE
Okay, now that we know it works. Try the following : Add a class to #personPopupContent e.g. class="popupContent" . Change the line of code where you set the html to call the class selector instead of the ID selector. Then to make sure that jQuery is getting the html element to add the content to, add some text to it.
//All the other code
+ ' <td><div id="personPopupContent" class="popupContent"></div></td>'
//All the other code
Change the selector in UserMouseOver() method :
$('.popupContent').html('<center><img src="images/loading_sm.gif" /></center>');
PLEASE MAKE SURE
I don't know where you are calling the UserMouseOver() method, so please add a Document Ready around the piece of jquery.
function UserMouseOver(o) {
//All the other code
$(function () {
$('.popupContent').html('<center><img src="images/loading_sm.gif" /></center>');
});
}

Categories

Resources