jQuery .click()/.on("click"...) I need help swapping text on alternate clicks - javascript

What I am trying to accomplish is something 'like'
$("button .toggleExcerpt)
.toggle( function FIRST() {
do first function...
} , function SECOND() {
do second function...
But since it's deprecated, I don't know what alternative to use. Ive tried using if/else inside of a .on("click", function()... but didn't seem to work.
jQuery:
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function (event) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
})
.on("click", function (event) {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
})
Both of the click events are logging to the console, so I know that the first event is running, and then is quickly replaced by the second event, but I would love to make these (or simply the text inside the span) to alternate....
I've already looked at this suggestion, but I am not sure how to implement it in my example, nor if this particular jQuery implementation is what I need.

To check the class is exists or not , you have to use .hasClass() . if class found,use .remove() to remove that element and .append() to add another.
For example, You can try this code :
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function (event) {
if($(this).find('span').hasClass('readmore') === true){
$(this).find('span.readmore').remove();
$(this).append(readLess);
}else{
$(this).find('span.readLess').remove();
$(this).append(readMore);
}
})

Check this snippet:
var readMore = "read about the solution...";
var readLess = "hide full description...";
var excerptState = true;
//".toggleExcerpt" is an empty <button> in the HTML
$(".toogleExcerpt").html(readMore);
$(".toogleExcerpt").click(function () {
$(this).html( excerptState ? readLess : readMore );
// invert state
excerptState = !excerptState
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toogleExcerpt"></button>

Why not try letting a boolean swap back and forth for you?
Here's your snippet:
$(document).ready(function() {
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
var more = true;
//".toggleExcerpt" is an empty <button> in the HTML
$("#toggleExcerpt").append(readMore);
$("#toggleExcerpt")
.on("click", function(event) {
if (more) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
more = false;
} else {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
more = true;
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="toggleExcerpt"></button>

I think I created a solution for you.
Just use a flag var that increments by 1, and check if it is odd or even and depending on if it is odd or even it will alternate the text for you onclick:
var readMore = "<span class='readMore'>read about the solution...</span>";
var readLess = "<span class='readLess'>hide full description...</span>";
//".toggleExcerpt" is an empty <button> in the HTML
var flag = 0;
$(".toggleExcerpt").append(readMore);
$(".toggleExcerpt")
.on("click", function(event) {
if (flag % 2 == 0) {
$(this).contents(".readMore")
.replaceWith(readLess);
console.log("readMore ran");
} else {
$(this).contents(".readLess")
.replaceWith(readMore);
console.log("readLess ran");
}
flag++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="toggleExcerpt" style="width:300px">

Related

how to exchange the attribute values simultaneously on single click event using jQuery

I want to replace #cardvieo_localstream with #cardvideo_remotestream at the first click, again I click the same element, I want to change #cardvideo_remotestream back #cardvieo_localstream, I'm not sharp at jQuery yet, but I'm trying to learn. I appreciate all help I can get.
I've try this code but working on first click. but not working on second click
$('.video-list .videoWrap').on('click', function() {
var $thisVideoWrap = $(this).find('.video-list .videoWrap');
var $mainVideoWrap = $('.mainVideoWrap');
if ($(this).attr('id') === '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_remotestream');
}
else if($(this).attr('id') == '#cardvideo_localStream') {
$(this).attr('id', '#cardvideo_local');
$mainVideoWrap.attr('id', 'cardvideo_remotestream');
}
});
Don't change An Id Attribute because of id is a unique value Only use the Classname, I swap the elements successfully
// using jQuery
var initVideoSwapping = function () {
// check if there is an element first
if ($('.video-list .videoWrap').length > 0) {
$('.video-list .videoWrap').on('click', function () {
var $thisVideo = $(this).find('video')[0];
var $mainVideo = $('.mainVideoWrap').find('video')[0];
swapNodes($thisVideo, $mainVideo)
});
}
}
function swapNodes(a, b) {
var aparent = a.parentNode;
var asibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aparent.insertBefore(b, asibling);
}
$(function () {
initVideoSwapping();
});

If an input contains custom word, hide the button

I have an input[type=text] area and i'll paste/type a URL in it.
If pasted/typed url contains http, i want to hide $('#button') element.
If its not, keep showing the button also.
Thanks for any help.
Here is my demo code so far:
$('#pasteUrl').on('input', function () {
var str = $('#pasteUrl').val();
if (str.indexOf("http") !== -1) {
$('#button').hide();
}
});
Edit: Added "propertychange" to events as suggested by OP in the comments.
$('#pasteUrl').on('input propertychange', function (ev) {
var str = $(ev.currentTarget).val();
if (str.indexOf("http") != -1) {
$('#button').hide();
} else {
$('#button').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="pasteUrl" />
<button id="button">Go</button>
This is likely what you want - using toggle:
$('#pasteUrl').on('input propertychange', function() {
var str = $(this).val();
$('#button').toggle(str.indexOf("http") == -1);
});

Checkbox unclick event Javascript

I have problem that checkbox uncheck event. When I unclick the checkbox it should be revert back. How can I do this?
<body>
<script>
function change()
{
var cb = document.querySelectorAll('input[type="checkbox"]')[0];
var td = document.querySelectorAll("td[contenteditable]")[0];
cb.addEventListener("click", function () {
td.className = td.className + " crossed";
});
}
</script>
</body>
Either toggle the class like:
cb.addEventListener("click", function () {
td.classList.toggle("crossed");
});
JSFiddle Demo
Or check if the checkbox is checked:
cb.addEventListener("click", function () {
if(cb.checked) td.classList.add("crossed");
else td.classList.remove("crossed");
});
JSFiddle Demo
If you want to keep the older browser support, you can do it like:
cb.addEventListener("click", function() {
if (cb.checked) td.className += " crossed";
else {
var tdclass = td.className.split(" "),
ind = tdclass.indexOf("crossed");
tdclass.splice(ind, 1).join(" ");
td.className = tdclass;
}
});
JSFiddle Demo
While you've already accepted an answer, I'd suggest a minor adjustment to the following:
function change() {
// querySelector() returns the first element matching the
// selector (or null, if no matching element is found):
var cb = document.querySelector('input[type="checkbox"]'),
td = document.querySelector("td[contenteditable]");
// use the change event on the check-box:
cb.addEventListener("change", function () {
// adds, or removes, the class 'crossed'
// based on the assessment that follows;
// of the cb node is checked (true) the
// class is added (if not already present),
// otherwise it's removed:
td.classList.toggle('crossed', cb.checked);
});
}
okay u want a tick to be re-enable when u click on it to unclick!!!
$("input[type='checkbox']").props('checked','false') {
$("input[type='checkbox']").props('checked','true')
}
Try to use a selector like id or something in place of: input[type='checkbox']

How to change class back after onclick

I'm creating a spoiler-tag script where the user clicks on spoiler text, the text will either blank out or change font-color depending on the class assigned to it. I'm rather a noob at Javascript.
My script only works when I click on the spoilered text when it is blank- so when I have already clicked on it, I can't reclick to change it back.
Here is the code that works:
// Hide Spoiler Individually
var singleHidden = document.getElementsByClassName("hidden");
var hideMe = function () {
var attribute = this.getAttribute("hidden");
this.className = "show";
};
for (var i = 0; i < singleHidden.length; i++) {
singleHidden[i].addEventListener("click", hideMe, false)
};
Here's a link on jsfiddle.
https://jsfiddle.net/o94c00hb/
Try this:
var hideMe = function() {
if(this.className == "hidden")
this.className = "show"
else
this.className = "hidden"
};
If you're not opposed to using jquery i would do something like this:
$('.hidden').on('click', function(){
$(this).toggleClass('show');
});
JSFIDDLE

Why is this javascript not working - select box if

I have this code on my site. The idea is to hide a specific class when a specific select box value is selected.
This is my code
$(document).ready(function(){
var txt = 'Marketing';
$("div.ginput_container select#input_3_1 option").each(function(){
if($(this).val()==txt){
$('.mar').hide();
}
});
});
The result I'm getting is .mar class being hidden as soon as the page is loaded. I can't see the error, I have also tryied with
var num = 1
but I have the same issue.
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
if ( this.value == txt ) $('.mar').hide();
});
});
Here's the fiddle: http://jsfiddle.net/9Cyxh/
If you want to show $('.mar') when a different option is selected, use toggle instead:
$('.mar').toggle( this.value != txt );
Here's the fiddle: http://jsfiddle.net/9Cyxh/1/
If you want this to also run on page load (before an option is manually selected), trigger the change event:
$(document).ready(function() {
var txt = 'Marketing';
$("#input_3_1").change(function () {
$('.mar').toggle( this.value != txt );
}).change();
});​
Here's the fiddle: http://jsfiddle.net/9Cyxh/2/
You don't need the loop in the first place
Attach your select to the change() event handler and that should be it..
$(document).ready(function(){
$("select#input_3_1").on('change', function() {
var txt = 'Marketing';
if(this.value === txt){
$('.mar').hide();
};
}).change()
});
If you only want to hide ".mar" class when the value is changed and it equals "Marketing" try
$("#input_3_1").change( function() {
if( $(this).val().toUpperCase() === "MARKETING" ) {
$(".mar").hide();
}
});
Demo here
$("#input_3_1").change(function(){
if ($("#input_3_1").val()=='Marketing'){
$(".mar").hide();
}
});

Categories