(jQuery) Find and Replace specific text - javascript

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.

Related

Issue with tree traversal, finding div ID to be used variably - jquery

so I've been trying to figure this out but I'm coming up short. Have really tried searching the best I could to come up with the answer, including jQuery API documentation and other SO posts. I feel like I'm almost there but I'm either misunderstanding something or I'm approaching this goal incorrectly.
For multiple different sections, I have 2 clickable icons in separate div's, 1 (lets say iconA) shown on load and 1 hidden (iconB) on load. When (iconA) is clicked, it hides the [sectionA] where (iconA) is located then shows the [sectionB] where (iconB) is located. I then want (iconB) to hide [sectionB] and show [sectionA].
Clearly I can't use toggle because one of the sections is always hidden at any given point. And since I'm trying to write a script that I can use for multiple sections and multiple icons, with different names, I can't just set 1-1 class names for ALL icons and sections.
I've created a jsfiddle to illustrate. Below I'll write a quick example.
HTML:
<div class="sectionAparent>
<div class="sectionA" id="example>
<i class="fa fa-code contbtn">iconA (shown on load)</i>
</div>
</div
<div class="sectionB" id="exampleSHOW">
<i class="fa fa-minus minushide">iconB (hidden on load)</i>
</div>
jQuery:
$('.contbtn').click(function(){
var contid = $(this).attr('id');
$('#'+contid+'show').slideToggle(1000);
$(this).hide(1000);
});
-this first one is to hide sectionA and show sectionB, which works fine.
$('.minushide').click(function(){
var cbtn = $(this).closest('.sectionB').siblings('.sectionAparent').find('div[id]');
var cid = $(cbtn).attr('id')
$('#'+cid+'show').slideUp(1000);
$(cid).slideDown(1000);
});
-So my thoughts were to jump up to the closest ancestor that is a sibling to the section containing the ID that I need. Then find the div with that ID, retrieve that ID, and use it show the section containing the ID and hiding the section with the ID+more. The goal is for this to be variable for multiple different sections with similar naming conventions without having to hard-code the section names in a list inside my script.
Hope this makes sense and I apologize for the wall of text, just wanted to make sure I conveyed what I'm trying to do and where I'm at. If my logic is incorrect or there is an easier way to do this, then I'm all ears! Thanks.
https://jsfiddle.net/dankbawls/wnjxwyfy/
You forgot to append the '#' character to sid in the second last line of the js
Updated fiddle
$('#'+sid).slideDown(2000);
Since you are using class (sectionhide) to toggle visibility, you can look into .toggleClass method.
It has an overriden constructor to accept 2 arguments, className and state (a boolean value)
Based on this state, it will add/remove class. True means add and false means remove
$('.minushide, .contbtn').on("click", function() {
var container = $(this).closest('.container');
var nextContainer = container.next('.container').length > 0 ? container.next('.container') : container.prev('.container');
container.toggleClass('sectionhide', true)
nextContainer.toggleClass('sectionhide', false)
})
Sample Fiddle
Note: I have added a common class container to both divs to have a common pattern
For a carousel kind of behaviour, you can use index to find index of element to be shown and hide all.
Sample Fiddle

Replace image in another div with text upon mouse over elsewhere

I have tried around a dozen different ways to do this, I'm only going to post my most recent attempts though.
Basically I am trying to have it so that when a user hovers the mouse over an image on the page, another image in a separate div gets replaced with text.
I have the JS variables for the text elements to replace as well as the original image being replaced to put it back.
My most recent attempts were:
function replaceMainPage(x) {
$('#logozone').empty();
$('#logozone').append(x);
}
function hoverCircles(y) {
$(this).hover(replaceMainPage(y), replaceMainPage(mainLogo));
}
I don't really understand the "this" feature of JS, but have also tried that function as:
function hoverCircles(y) {
$('#logozone').hover(replaceMainPage(y), replaceMainPage(mainLogo));
}
From here I have tried calling the function is my main JS file like so:
$("#cir1").hover(replaceMainPage(logoReplacements.cakes), replaceMainPage(mainLogo));
As well as tried doing it in html on the img element itself with a onmouseover. Nothing has worked yet.
Am also open to non-JS ways of handling this, but I looked for those as well and couldn't find anything.
This will help you, here is a jsFiddle:
var oldContent = '';
$('.hoverMe').hover(function() {
oldContent = $('.toReplace').html();
$('.toReplace').html('xxxxxxxx');
}, function() {
$('.toReplace').html(oldContent);
});
HTML
<div class="hoverMe">
HOVER ME
</div>
<div class="toReplace">
<img src="//cdn2.hubspot.net/hub/360031/hubfs/feature_practicetest.jpg?t=1470774914678&width=365">
</div>
I've created a global variable called oldContent. When hover on the .hoverMe div, store the old content of that div, change the content of div, and when you move your mouse out, put back the old content.
UPDATE
Based on OP comment, I create another jsFiddle where you can set any text on the .hoverMe
If there are longer texts, or kind of texts what can not be stored in the data attribute, then add data-id="1" to n, and retreive the text through ajax based on the id.
HTML
<div id="firstImgDiv">
<div class="text"></div>
<img src="a.png" onmouseenter="replaceImg('secondImgDiv', 'new Text')">
</div>
<div id="secondImgDiv">
<div class="text"></div>
<img src="b.png" onmouseenter="replaceImg('firstImgDiv', 'new Text')">
</div>
JS
function replaceImg(id, text){
// show all images again
$('img').show();
// clear all text
$('.text').html('');
// hide target img
$('#'+id+' > img').hide();
// set target text
$('#'+id+' > .text').html(text);
}

A function with changing variable, dependent on a class

So, first some background.
I have 9 types of rooms that are displayed as thumbnails with the name. What I want to do is that on click "Additional Information" - the rooms with disappear and the expanded version of a chosen room type will appear with the description and bigger picture. Also, there is an ability to go next and previous in the expanded view. I do not have a problem with this expansion and previous/next. BUT!
Here is what I am trying to achieve: if the code looks approximately like
<ul id="room_holder">
<li><div class="room 1">Additional Info</div></li>
<li><div class="room 2">Additional Info</div></li>
and so on...
And the expandable area will look something like:
<div id="expandable">
<div id="picture">Blah-blah-blah, some description, etc</div>
</div>
So, basically, what I can't figure out is how to get the needed slide to show when the correspondint thumbnail is pressed. I know I can do the .addClass method, and copy the code 9 times, for each of the numbers (1-9). But I believe it is 9 times more compact if I have some sort of function, that gets the second class name (the number) by using .split(' ')[1] and then using it as part of the variable in the part which opens the corresponding expandable view. So, my question is: how do I do this? I am a newbie with javascript, but try to learn on the go!
Oh, and the codepen that I've been trying to deal with is:
http://codepen.io/godban/pen/QbZmxz
Firstly, you should use data-* attribute instead of classes (new in HTML5) data attributes, w3school :
<ul id="room_holder">
<li><div class="room" data-room="1">Additional Info</div></li>
<li><div class="room" data-room="2">Additional Info</div></li>
Then, use the click function from jQuery .click( handler ), use it this way to know which one has been clicked :
$(".room").click(function(event){
var target = event.currentTarget;
var room = $(target).data("room");
alert(room);
});

add class to element from another page

I need to add a class (.open) to an element (h2) on another page from the home page depending on which option is clicked.
The jquery below shows a line of code that i've written which although doesn't work gives you an idea of what i'm trying to do.
Jquery
//open service section from home page
var hash = window.location.hash;
if(hash != "") {
var id = hash.substr(1);
document.getElementById(id).style.display = 'block';
//document.getElementById(id).previous('h2').addClass( "open" ); //CODE THAT DOESN'T WORK
}
HTML (This is what i'm trying to ahceive. As you can see the h2 contains the .open tag)
<h2 class="section-heading toggle open">heading title</h2>
<div id="content1" class="slide-content"></div>
</div>
You're mixing up the DOM and jQuery. I suggest using one or the other.
The jQuery way to write the commented out "code that doesn't work" line is
$(hash).prev().first().addClass("open");
or
$(hash).prevAll('h2').first().addClass("open");
...if there's any chance of an element between the one with the ID and the h2.
Note I used hash rather than id, since it has the # on it, and conveniently that's how you select by id in CSS.

Getting HTML content using jQuery on click

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

Categories

Resources