Select interact to a specific html element with a button - javascript

I have a few buttons in the HTML file code with Bulma similar like this:
<a class="button" data-target="A">Section A</a>
<a class="button" data-target="B">Section B</a>
<a class="button" data-target="C">Section C</a>
And there are a few section like this which can interact with the buttons:
<div id="A" class="contentswitch">
<article class="message">
<div class="message-header" id="h1">
<p>Section A-1</p>
</div>
<div class="message-body">
Message 1 of section A
</div>
<div class="message-header">
<p>Section A-2</p>
</div>
<div class="message-body">
Message 2 of section A
</div>
</article>
</div>
As I add code like this in the JS, it can add a class called "is-hidden" to all the div ejectment which contains "contentswitch" class.
$("a.button").on("click", function(){
$("div.contentswitch").addClass("is-hidden");
});
What can I do if I want to remove the class ("is-hidden") from specific div element, like if I click the button of Section A, then it add "is-hidden" class to all the div element contain content switch then remove it from the div element with the id "A"?
Thank you so much

You can use data-target to connect the clicked button to the div you want to show. And hide the rest of them.
Also, use button iso a tag. a tag has a specific purpose in HTML and should be used only in combination with href attribute.
const buttons = $('.button');
const contentSwitchDivs = $('.contentswitch');
buttons.on("click", function(){
const btnTarget = $(this).data('target')
const contentToShow = $(`#${btnTarget}`)
contentSwitchDivs.not(btnTarget).hide();
contentToShow.show();
});
.contentswitch {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button" data-target="A">Section A</button>
<button class="button" data-target="B">Section B</button>
<button class="button" data-target="C">Section C</button>
<div id="A" class="contentswitch">
A contentswitch
</div>
<div id="B" class="contentswitch">
B contentswitch
</div>
<div id="C" class="contentswitch">
C contentswitch
</div>

Related

how to target the element above my show more button

i want to target the element above my show more button, so when i click the button more text appears i don't want to target it by class name or id
here is my code
<div class="ccontainer" id="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button id="showmore" onclick=" this.parentElement.style.maxHeight = 'none'"> show more </button>
Don't refer to the IDs that can get cumbersome. Instead give your show more button a class to refer to. That will give you the ability to add many to the same page without needing to adjust/track the IDs.
This is a basic example that toggles a class on the content div that will show the full div. Obviously the details are up to your specific needs.
Using previousElementSibling allows you to refer to the previous element.
document.addEventListener("click",function(e){
let btn = e.target;
if(btn.className.indexOf("showmore") > -1){
btn.previousElementSibling.classList.toggle("active");
}
});
.ccontainer{
height:50px;
overflow:hidden;
border:1px solid #000;
margin:10px 0;
padding:10px;
}
.ccontainer.active{
height:auto;
}
<div class="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button class="showmore"> show more </button>
<div class="ccontainer">
<p id="context"> content3 </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content4 </p>
</div>
<Button class="showmore"> show more </button>
When using jQuery you can use:
$(this).prev(); // $(this) is equal to the button
// or very specific
$(this).prev(".container");
Using vanilla JS you could use something like
onclick="this.previousSibling"
not sure if vanilla js has a way of selecting a previous node by identifier.
Any whitespace or comment block is also considered a previousSibling, so be careful with that.
html
<div>
<div class="ccontainer" id="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button id="showmore" onclick="hideParent(this)"> show more </button>
</div>
js
function hideParent(elm){
console.log(elm.previousElementSibling.innerHTML )
}
see https://jsfiddle.net/rkqnmv0w/
If your using only vanila JS you can access the previous element with the previousElementSibling property.
Example:
var showMoreButton = document.getElementById('showmore');
var previousElement = showMoreButton.previousElementSibling;

Toggle next section

I have a block of HTML:
<form>
<section>
<div class="row normalTopPadding personalInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
<section>
<div class="row normalTopPadding employerInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
<section>
<div class="row normalTopPadding accountInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
</form>
What I'm trying to achieve is for every time a button is clicked to hide the panel that the button has been clicked from and display the next panel down, so..
<script>
$('.personalInfomation .reg-next-button, .employerInformation .reg-next-button', .accountInformation .reg-next-button').click(function (e) {
// Get the section that this button lives in
var form = $(this).closest("section");
//validation and other functions commented out for ease of reading
// Hide this section...
section.toggle();
// And show the next section
section.next().toggle();
});
</script>
Although this hides the section that the button has been clicked from it doesn't display the next one down.
Could someone point out my mistake?
Thanks,
C
you can check if next section is available or not and then hide current section.
NOTE: there is extra single quote in your jquery selector, which i have removed. Also, you have declared variable form but used section, so rename form to section
$('.personalInfomation .reg-next-button, .employerInformation .reg-next-button, .accountInformation .reg-next-button').click(function (e) {
// Get the section that this button lives in
var section = $(this).closest("section");
//validation and other functions commented out for ease of reading
// Hide this section...
var $next = section.next();
if($next.length>0) { // check condition first and then hide current section and show next
section.toggle();
// And show the next section
$next.toggle();
}
});
Instead of putting each section in button click handler you can generalise it and improve your code so that when you add new section you don't need to change your script.
NOTE - do not use same id for multiple html elements as you have used it for button
$(function(){
$('section .row.normalTopPadding .reg-next-button').on('click', function (e) {
var section = $(this).closest("section");
var $next = section.next();
if($next.length>0) { // check condition first and then hide current section and show next
section.addClass('hide');
$next.removeClass('hide');
}
});
});
.hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<section>
<div class="row normalTopPadding personalInfomation">
<!--Loads of HTML and Stuff-->
This is SECTION 1
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
<section class="hide">
<div class="row normalTopPadding employerInfomation">
<!--Loads of HTML and Stuff-->
This is SECTION 2
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
<section class="hide">
<div class="row normalTopPadding accountInfomation">
<!--Loads of HTML and Stuff-->
This is SECTION 3
<a id="myButton" class="reg-next-button btn btn-default">Next</a>
</div>
</section>
</form>
You may try to hide all the sections first, and then on click of a, find the next .row to be shown.
See the demo below:
$('.row').not(':first').css('display', 'none');
$('.row > a').click(function() {
$(this).parents('.row').toggle();
$(this).parents('section').next('section').find('.row').toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<section>
<div class="row normalTopPadding personalInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next 1</a>
</div>
</section>
<section>
<div class="row normalTopPadding employerInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next 2</a>
</div>
</section>
<section>
<div class="row normalTopPadding accountInfomation">
<!--Loads of HTML and Stuff-->
<a id="myButton" class="reg-next-button btn btn-default">Next 3</a>
</div>
</section>
</form>

Loop thru each anchor and onclick display an image in modal box using jQuery

I have dynamically generated div's whose content contains an anchor link and path to an image.
I also have a modal box with an image tag in.
What I am trying to do is onclick of the anchor link, set the image tag path which is in the modal box.
Currently what my code does is no matter what anchor link I click, its always setting image path to the first path link.
Here is my JSFiddle link
JSFiddle
My Code:
<div id="coupon-listing-items" class="shopping-listings listings">
<div class="left-split">
<a class="ads-links" title="Test Title One" href="http://www.test.com/"><h2>Test Title One</h2></a><div class="coupon-text">(Get 20% of by staying 2 nights)</div>
<span id="sLink" class="hide">http://via.placeholder.com/350x250</span>
</div>
<div class="left-split">
<a class="ads-links" title="Test Title Two" href="http://www.test.com/"><h2>Test Title Two</h2></a><div class="coupon-text"></div>
<span id="sLink" class="hide">http://via.placeholder.com/400x350</span>
</div>
</div>
<!-- Modal Box -->
<div class="modal CouponModal">
<span class="close-modal">×</span>
<div class="modal-content">
<input type="button" class="btnprint" name="btnprint" value="Print This Coupon" onclick="PrintC('cp-image')"/>
<div id="cp-image">
<img id="coupon-image" />
<div id="caption">
<span class="vist">Visit the website: <a id="c-weblink"></a></span>
</div>
</div>
</div>
</div>
$(".ads-links").each(function(index){
$(".ads-links").on("click", function(e){
e.preventDefault(); var imgsrc = document.getElementById('sLink')
$(".CouponModal").css('display', 'block');
$("#coupon-image").attr('src',imgsrc.innerHTML);
});
$(".close-modal").click(function(e) {
$(".CouponModal").css('display', 'none');
});
});
If you click on Test title one, you will image name 350x250 displayed in the modal box, and if you close the modal box and now click on test title two, instead displaying the image 450x350 just displays the first image.
What am I missing?
Thanks and appreciate it
You are selecting the first sLink no matter which is anchor is clicked.
var imgsrc = document.getElementById('sLink');
Instead you need to base this on the sLink closest to the anchor clicked.
var imgsrc = $(this).parent().find('#sLink')[0];
//This goes up a level and finds the sLink that is in that same parent//
Note
that an ID should be unique and is likely causing part of your confusion, in this case a class might be just as useful.
your outer loop is superfluous and might cause you trouble down the road.
Updated Your Fiddle: https://jsfiddle.net/0dmc9rvt/25/
$(".ads-links").each(function(index) {
$(this).on("click", function(e) {
e.preventDefault();
debugger;
$(".CouponModal").css('display', 'block');
$("#coupon-image").attr('src', $(this).parent().find('.sLink').html());
});
$(".close-modal").click(function(e) {
$(".CouponModal").css('display', 'none');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="coupon-listing-items" class="shopping-listings listings">
<div class="left-split">
<a class="ads-links" title="Test Title One" href="http://www.test.com/">
<h2>Test Title One</h2>
</a>
<div class="coupon-text">(Get 20% of by staying 2 nights)</div>
<span class="hide sLink">http://via.placeholder.com/350x250</span>
</div>
<div class="left-split">
<a class="ads-links" title="Test Title Two" href="http://www.test.com/">
<h2>Test Title Two</h2>
</a>
<div class="coupon-text"></div>
<span class="hide sLink">http://via.placeholder.com/400x350</span>
</div>
</div>
<!-- Modal Box -->
<div class="modal CouponModal">
<span class="close-modal">×</span>
<div class="modal-content">
<input type="button" class="btnprint" name="btnprint" value="Print This Coupon" onclick="PrintC('cp-image')"/>
<div id="cp-image">
<img id="coupon-image" />
<div id="caption">
<span class="vist">Visit the website: <a id="c-weblink"></a></span>
</div>
</div>
</div>
</div>

<a> element not working properly when hiding parent?

I made this script, and despite one oddity, it works fine. It's hiding/showing the parent of div element with a class containing specific content. The problem when I press my <a> elements, that act as buttons, they "filter" the divs, but it leaves the first comment <a>? If I change the element do a <div> instead no problem, but with an <a> element it behaves weirdly? Is this just a bug or?
here is a JSFiddle: https://jsfiddle.net/g1puxhs7/2/
HTML:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
</div>
<style>
.row {
width: 200px;
margin: 10px;
background: #ccc;
padding: 4px;
}
</style>
SCRIPT:
//--Filter by Status--//
$('.viewBtn').click(function() {
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});
The problem is with your links:
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
You have 6 opening a tags, instead of 3 opening and 3 closing tags.
This is why the browser adds closing a tags in your script in a bunch of places, one of them in your first div—and then your whole DOM tree looks different than what you want.
Your markup needed to be cleaned up. Here is your markup cleaned up. Also, i find it best to add href for you anchor tags, and then you can comment them out with #, or you can add javascript:void(0). If you use the # approach, in your JS, you can add e.preventDefault();
HTML Cleaned:
<div>
<a class='viewBtn' href="#">Published</a>
<a class='viewBtn' href="#">Completed</a>
<a class='viewBtn' href="#">Created</a>
</div>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff" onclick="Comment">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
</div>
JS with preventDefault():
$('.viewBtn').click(function(e) {
e.preventDefault();
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});

Apply style by javascript without using Id

My html page content is below
<div>
<div>
Summary 1
</div>
<div style="display:none">
Details 1
</div>
<button>Read More</button>
</div>
Details content is collapsed initially. When user clicks the Read More button, I need to show details content. I can make it possible. i will define id for details div tag and javascript for onclick event of button. Using id i will change the div style display.
But i have multiple list of sections based on the back end data. so my page would be renderd like below
<div>
<div>
Summary 1
</div>
<div style="display:none">
Details 1
</div>
<button>Read More</button>
</div>
<div>
<div>
Summary 2
</div>
<div style="display:none">
Details 2
</div>
<button>Read More</button>
</div>
<div>
<div>
Summary 3
</div>
<div style="display:none">
Details 3
</div>
<button>Read More</button>
</div>
Now How can i acheive the expand and collapse functionality when Read More button is clicked.
Using plain javascript and with the strategic addition of some classes, you could do this which would make each button into a toggle that even changes it's text according to the toggle state. Then one piece of javascript would serve for all the repeated instances of this structure and the code would be independent of the exact HTML layout of the summary, details and button (as long as they retained the same classes and were in the same container div.
HTML:
<div>
<div>
Summary 1
</div>
<div class="details" style="display:none">
Details 1
</div>
<button class="readMore">Read More</button>
</div>
<div>
<div>
Summary 2
</div>
<div class="details" style="display:none">
Details 2
</div>
<button class="readMore">Read More</button>
</div>
<div>
<div>
Summary 3
</div>
<div class="details" style="display:none">
Details 3
</div>
<button class="readMore">Read More</button>
</div>​
And the javascript:
function toggleVis(el) {
var vis = el.style.display != "none";
if (vis) {
el.style.display = "none";
} else {
el.style.display = "block";
}
return(!vis);
}
(function() {
var readMore = document.getElementsByClassName("readMore");
for (var i = 0; i < readMore.length; i++) {
readMore[i].onclick = function(e) {
var vis = toggleVis(e.target.parentNode.getElementsByClassName("details")[0]);
e.target.innerHTML = vis ? "Read Less" : "Read More";
}
}
})();
Working Demo: http://jsfiddle.net/jfriend00/aMBkJ/
Note: This would require a shim for getElementsByClassName() on older versions of IE.
​
By using jQuery .prev() you may achieve it easily.
$('button').on('click', function(e){
$(this).prev('div').toggle();
});
DEMO
You can try this with jquery
<button class="readmore">Read More</button>
jQuery
$('.readmore').click(function(){
$(this).prev().show();
});
Here it is how you do it using jquery:
The HTML code:
<div class="stuff">
<dl id="faq">
<dt>What shouldn't I do to the bird?</dt>
<dd>Never try to treat a fracture at home.</dd>
</div>
The JQuery code:
jQuery(document).ready(function() {
$('#faq').find('dd').hide().end().find('dt').click(function(){
$(this).next().slideToggle();
});
});

Categories