Getting HTML content using jQuery on click - javascript

I've got a simple application that requires a DIV to be clicked, and in turn it shows another DIV which needs to have its content updated.
There are around 40 items that will need to be clickable and show the correct label for each.
Here is what I need to happen...
User clicks a DIV (drag_me)
Information box DIV is then shown (flavour_box)
the default word 'Ingredients' is swapped out with the content from the "flavour_descrip" div
Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
The data comes from a database, so I'm unable to set individual ID's.
I had a similar issue with draggable's, but that was fixed, and I've tried doign somethign similar to no avail.
Here is the clickable DIV (flavour_descrip is set as hidden in the CSS)
<li class="drag_me">
<div>
<img src="RASPBERRY.png" />
</div>
<div class="choc_label">
Raspberries
</div>
<div class="flavour_descrip">
Our description will appear here for the DB
</div>
</li>
Here is the HTML for the popup box...
<div id="flavour_box">
<p class"flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
Here is the jQuery snippet for the click (i've commented out the code I had started to rejig, but essentially I need to change the draggable.find to something that will work!)
$(".drag_me").click(function () {
//var htmlString = ui.draggable.find('.choc_label').html();
//$('.choc2_flavour').text(htmlString);
// update the description of the item
//var htmlString = ui.draggable.find('.flavour_descrip').html();
//$('.flavour_description').text(htmlString);
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
Any ideas how I can achieve this?
Added extra question
Now I've had my problem resolved, I need to perform one more task.
Inside the div that gets the details passed using "this", I need to be able to pass one more items to a different piece of script.
The DIV 'flavour_add' is clickable and will need to grab the flavour name to use to update some bits on screen and update a URL on the fly.
<div id="flavour_box">
<p class="flavour_name_label">Label</p>
<p class="flavour_description">Ingredients</p>
<div class="flavour_add">Add To Mixing Bowl</div>
</div>
This is the jQuery I have, but using "this" doesn't seem to work
$(".flavour_add").click(function () {
// hide the ingredient box
$("#flavour_box").toggleClass("hidden");
// show the continue box
$("#added_box").toggleClass("visible");
// get the flavour name
var flavourLabel = $(this).find('.flavour_name_label').text();
// update flavour URL
var _href = $("a.to_step_3").attr("href");
$("a.to_step_3").attr("href", _href + '&flavour=' + flavourLabel);
//$("a.to_step_3").attr("href", _href + '&flavour=TestFromAdd');
// update the mixing bowl list with the ingredient
$('.choc2_flavour').text(flavourLabel);
});

Use $(this) to get the reference to the clicked element:
$(".drag_me").click(function () {
var txt = $(this).find('.choc_label').text();
$("#flavour_box > .flavour_descrip").text(txt);
$("#flavour_box").toggleClass("visible");
});
Besides, there was a "typo" in your html code, replace:
<p class"flavour_description">Ingredients</p>
By:
<p class="flavour_description">Ingredients</p>

You can easily achieve this using jQuery.
$(".drag_me").click(function () {
$('.flavour_description').text($('.flavour_descrip').html());
// on click of jar make box pop
$("#flavour_box").toggleClass("visible");
});
I cannot seem to be able to find the divs for step: 4. Also update the 'choc_flavour' div with the name of the ingredient (choc_label)
I will assume that you mean 'flavour_add' in which case the code should look like this:
$('.flavour_add').text($('.choc_label').html());

Try this:
$(document).ready(function() {
var $flavourBox = $('#flavour_box');
var $flavourDesc = $flavourBox.children('.flavour_description');
var $chocFlavour = $flavourBox.children('.choc_flavour');
$('.drag_me').on('click', function() {
var $this = $(this);
$flavourDesc.html($this.children('.flavour_descrip').html());
$chocFlavour.html($this.children('.choc_label').html());
$flavourBox.addClass('visible'); //toggleClass will remove the class if it is there
});
});

get the text by using "this" (the actual clicked element) and then get the child flavour_descrip div
$(".drag_me").click(function () {
$("#flavour_box").show();
$('.flavour_description').text($(this).find('.flavour_descrip').text());
});
then show the flavour_box div and set the value of the div with the flavour_description class

Related

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

javascript click image display

What I'm trying to do is, when one of six divs is clicked, a separate div will have 3 specific divs appear in it. Each of the original six divs have three similar but different divs related to it.
http://jsfiddle.net/petiteco24601/hgo8eqdq/
$(document).ready(function () {
$(".talkbubble").mouseout(function(){
$(".sidebar").show();
});$
$(".talkbubble").click(function(){
$
How do I make it so that when you click a "talkbubble" div, a different "sidebar" div appears with all its contained elements, and when you mouseout, the first talkbubble div automatically activates?
Here is a demo of how to do this: http://jsfiddle.net/n1xb48z8/2/
The main part of this example is some javascript that looks like this:
$(document).ready(function(){
showSideBar(1);
$('.expander').click(function(){
var sidebarIndex = $(this).data('sidebar-index');
showSideBar(sidebarIndex);
});
$('#Container').mouseleave(function(){
showSideBar(1);
});
});
function showSideBar(index){
$('.sidebarContent').hide();
$('.sidebarContent[data-index="' + index + '"]').show();
}
.data('some-name') will get you the attribute data-some-name="" on the specific element, this is a html 5 attribute and if you do not want to use it you can instead give each of the elements their own class names such as:
<div class="sidebarContent subBarContent_1">
<!-- content -->
</div>
and use the '.subBarContent_1' as your jquery selector instead. You would then also have to have some sort of data attached to your clickable divs to identify which one you wanna show, you could use a hidden field to do that like:
<input type="hidden" class="subContentSelector" value="subBarContent_1" />
The javascript for that looks like this:
$(document).ready(function(){
showSideBar(1);
$('.expander').click(function(){
var sidebarSelector = $(this).find('.subContentSelector').val();
showSideBar(sidebarSelector );
});
$('#Container').mouseleave(function(){
showSideBar('subBarContent_1');
});
});
function showSideBar(selector){
$('.sidebarContent').hide();
$('.sidebarContent.' + selector).show();
}
Ps. the overflow:hidden css is because chrome was messing up the placement of the sidebar content otherwise... oh chrome, you silly goose

Show and Hide DIV based on users input

I have an input box for zip code entry's, when a user inputs a zip code I want to show a specific DIV.
It starts with everything hidden except for the input box and go button, then the user enters a zip code and the matching DIV shows (the DIV ID will be the zip code) There maybe hundreds of DIVs and possible inputs.
Here is what I have so far, note it starts showing everything (not what I want) but it kinda works
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == 60538) {
$("#60538").show("fast"); //Slide Down Effect
$("#60504").hide("fast");
}
else {
$("#60538").hide("fast"); //Slide Up Effect
$("#60504").show("500");
}
});
$("#full_day").change(function() {
$("#60504").hide("500");
$("#60538").show("500");
});
});
LINK to working File http://jsfiddle.net/3XGGn/137/
jsFiddle Demo
Using pure numbers as id's is what was causing the issue. I would suggest you change them to
<div id="zip60538">
Welcome to Montgomery
</div>
<div id="zip60504">
<h1>Welcome to Aurora</h1>
</div>
In the html (as well as in the css and the js as can be seen in the linked fiddle)
This will allow them to be properly referenced in the DOM
edit
jsFiddle Demo
If you had a lot of these to handle, I would probably wrap the html area in a div to localize it and then use an array to store the accepted zip codes, and make use of both of those approaches in the click event
$(document).ready(function(){
var zipCodes = [60538,60504];
$("#buttontest").click(function(){
var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
$("#zipMessage > div").hide("fast");
$("#zip"+zipCodes[zipIndex]).show("fast");
});
});
Start off with all the div's style of display: none;. On your button click simply check that a div exists with that ID, if so, hide all others (use a common class for this) and show the right one:
$("#buttontest").click(function() {
var zip = $("#full_day").val();
if ( $("#" + zip).length ) {
$(".commonClassDiv").hide();
$("#" + zip).show();
}
});

Saving ID for specific onclick element

I'm trying to create a JavaScript where you write a message and the time and message appears on the website. The function doing this is "renderMessage". However, it includes an image you can click to delete that message and then I want to write all the remaining ones again. Problem is that I don't know how to save some sort of ID so I know which image was clicked so I delete the correct position in the array of messages.
The code for renderMessage is:
function renderMessage(theMessage, theMessages){
var text = document.createTextNode(theMessage.getText());
var time = document.createTextNode(theMessage.getDate());
var div = document.getElementById("writeMessages");
div.appendChild(text);
div.appendChild(time);
var image = document.createElement('img');
image.src = 'img/deletePic.png';
div.appendChild(image);
div.appendChild(document.createElement('br'));
image.onclick = function(e){
theMessages.splice(); // This is where I don't know how to remove the correct one
removeAll(theMessages); // This removes all html code in the div and writes
// the array again (hopefully this time with the correct
// element removed from it)
};
}
Firstly, thumbs up for using plain js.
I would say you enclose the message, time and the image into another element. My be a ul li block. And, when you render the messages in DOM, you set the message id as id attribute of the li so it will be something like this
<ul>
<li>Message 1 - 10:21 PM <img src="remove jpg"/></li>
<li>Message 2 - 10:22 PM <img src="remove jpg"/></li>
</ul>
and your js code can be,
image.onclick = function () {
var message_id = this.parentNode.id;
// here you got the message id.
// splice your message array and render
}
Why are you re-rendering all the messages? You could simply
// splice your message array and render
var li = this.parentNode;
li.parentNode.removeChild(li);
}
you can save the id of the message inside an attribute of the element. eg <div class="your_message_container data-id="14">...</div>
Using jquery for example you can read that attribute with $(your_selector).attr("data-id"); and write it with $(your_selector).attr("data-id", "new_value");
As an alternative, also have a look at http://api.jquery.com/jquery.data/
Edit:
i made you a fiddle with pure js: http://jsfiddle.net/A64zh/2/ Note that the id of the message element must equal the data-message-id attribute of your delete image.
the advantage of using an element attribute for storing the id is that your javascript does not depend on the html structure like it does if you are using something like this.parentNode.parentNode.removeChild.... which would need to be changed if you would add more html layers in between the two

(jQuery) Find and Replace specific text

I've got the following HTML code, which essentially pertains to a post where I announce something in just a few lines, end it with "[...]", and add a "Read more" link-button at the bottom. When this button is clicked, additional content that's hidden will fadeIn as the button disappears, leaving visible the introductory text and the one that was hidden -- simple enough. Now, I've already written the code for this, but the complication comes when I try to also remove that "[...]" (from the post where the click button happened) that I included in the sneak peek. Here's the HTML:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span id="revealer" class="button">Read more</span>
</div>
Classes "entry" and "button" belong to my CSS file, while "slide-content" belongs to my .js file to control the fadeIn effect. The ID "revealer" also belongs to the .js file for the same purpose. This HTML is wrapped in a div tag with a class of "box". This is the format that each post follows, exactly the same format with the same HTML elements -- every time an announcement needs to be made, it's just a matter of putting the content between the paragraph tags and publish. Here is where my problem comes in, since I can't find a way to remove the "[...]" only in the post where the button has been clicked. I tried doing the following but it resulted in the deletion of all "[...]" throughout multiple posts:
$('.entry p').each(function() {
var textReplace = $(this).text();
$(this).text(textReplace.replace('[...]', ''));
});
Summary:
I need to remove the "[...]" text only from the post where the user has clicked on (the "Read more" button). The idea is to have this removed while at the same time the hidden content fades in.
I've been able to accomplish the above but for all instances of "[...]". I need to sophisticate my selection by modifying my jQuery code or the HTML.
Option 3 is to get rid of this "[...]", but I would like to leave it there to let the user know she has more content to read, and I would like to have that "Read more" button in all posts for consistency.
~Thanks in advance!
First, you mention you have multiple of these. In that case, this:
<span id="revealer" class="button">Read more</span>
will not work. id attribute has to be unique per document, i.e. you can have at most one element with the specific id value.
If you make your HTML (for each of the blocks) like this:
<div class="entry">
<p>Welcome. Talk about something briefly and click below for more. [...]</p>
<div class="slide-content">
<p>Hidden content.</p>
</div>
<span class="revealer button">Read more</span>
</div>
and your JS like this:
function replace(fromp) {
var textReplace = fromp.text();
fromp.text(textReplace.replace('[...]', ''));
}
$('.revealer').click(function() {
var fromp = $(this).siblings().eq(0);
replace(fromp);
});
it will work properly. Working example:
http://jsfiddle.net/G4t7Q/
Hope this helps.
When you run your page initialization script, you could use jquery to select all of the posts and all of the remove buttons and link them up via their click event. I've created a JSFiddle example, but here's the jist of it:
var removers = $(".remover")
var posts = $(".post")
for (var i = 0; i < removers.length; i++) {
$(removers[i]).click( { post: posts[i] },
function(event) {
var textReplace = $(event.data.post).text()
$(event.data.post).text(textReplace.replace('[...]', ''))
}
)
}​
This is a simplified example; it assumes the posts and buttons are sorted in the markup.

Categories

Resources