I am trying to toggle a link texts and content when user clicks the link.
I have something like
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
})
When user click the link, the link text will become isClicked and the items html will be replaced with a image. However, if user clicks again, I want to see the link text changes back to click me and the items will hide the image and display the title and p tag contents again.
I am not sure how to accomplish this. Can anyone help me about it? Thanks a lot!
You can add a dummy class to the link and work with that condition
//Have a dummy class added to the link and toggle it on click
$('#link').on('click', function(e){
e.preventDefault();
var $this = $(this),
$textDiv = $('#items'),
$imageDiv = $('#image')
if($this.hasClass('clicked')) {
// remove the class
$this.removeClass('clicked');
// change the text
$this.text('click me');
// Hide image
$imageDiv.addClass('hide');
// show text
$textDiv.removeClass('hide');
} else {
// remove the class
$this.addClass('clicked');
// change the text
$this.text('isClicked');
// Show image
$imageDiv.removeClass('hide');
// Hide text
$textDiv.addClass('hide');
}
});
Check Fiddle
You can also chain the methods applied on the same element.
$('#link').on('click', function(e){
e.preventDefault();
if ($(this).text() == "isClicked") {
$(this).text("click me");
.. etc
} else {
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
}
});
Like I said in my comment, use a condition like this. Simple and effective.
One way you could do it:
$('#link')
// Set data attribute to hold original text
.data('primeText', $('#link').text())
// set click event using jQuery1.73+
.on('click', function(e) {
e.preventDefault(); // prevents going to link, not needed if you set link href to "javascript:void(0)"
// begin setting text, within is a inline-if statement testing current text against prime text
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Another way, if you were working with more than one, like using a class name instead of ID:
$('.link')
// jQuery's .each method allows you to do things to each element in an object group
.each(function(i) { $(this).data('primeText', $(this).text()); })
// again, calling click method
.on('click', function(e) {
$(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});
Examples
What about using a CSS approach?
Your HTML would stay the same:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
But we can use .toggleClass() here to make our lives easier
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').toggleClass('display-image');
})
The CSS would look like:
#items.display-image > h1,
#items.display-image > p,
{
visibility:hidden;
}
#items.display-image{
background-image:url("/images/image.png");
}
This way, you don't have to worry about removing things and .toggleClass handles their visibility.
You might have to do additional styling to get the image to work properly, or you may consider adding another element to contain the image and you can just set its visibility or display property
Try something like this:
HTML:
<a id='link' href='#'>click me</a>
<div id='items'>
<h1 class="text-item">title here</h1>
<p class="text-item">texts here...</p>
<img src="images/images.png" alt="Image" />
</div>
CSS:
img {
display: none;
}
JavaScript:
$('#link').off().on('click', function(e) {
e.preventDefault();
if($('#items > img').is(':visible')) {
$(this).text('click me');
$('#items > img').hide();
$('#items > .text-item').show();
} else {
$(this).text('isClicked');
$('#items > .text-item').hide();
$('#items > img').show();
}
});
Fiddle
You can try to store the value in a var and then toggle with on off in functions themselfs;
var initialState = $('#items').html(),
functionBla(e) {
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
$('#link').off('click').on('click', functionCla);
},
functionCla(e) {
e.preventDefault();
$(this).text('click');
$('#items').html(initialState);
$('#link').off('click').on('click', functionBla);
};
$('#link').on('click', functionBla);
You can do it like,
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').children().toggle();
var img=$('#items img');
if(img.length>0){
img.remove();
}
else{
$('#items').append("<img src='images/image.png' />");
$(this).text('Click me');
}
})
Related
Jsfiddle at demo.
I have a contenteditable div. I want the html of whatever I write in that div, on the click of anchor tag.
Right now, div is working but nothing is showing on click of the anchor tag.
function getcode()
{
var content = $('#my-contenteditable-div').html();
alert (content);
}
You can do this as well:
$("a").click(function () {
alert($('#my-contenteditable-div').html());
});
Here is the JSFiddle
Then you don't need to write separate functions and attach it to the onclick event attribute of the a tag
Try This
// get the link
var link = document.getElementById("linkId");
// add click listener to it
link.addEventListener("click",getcode,false);
// you handler
function getcode()
{
var content = document.getElementById("my-contenteditable-div");
alert (content.innerHTML);
}
Just you can go with jquery
Working Fiddle
$(document).ready(function() {
$('#gethtml').on('click', function(e) {
var content = $('#my-contenteditable-div').html();
alert (content);
});
});
can use this use id in a and a div to show data
<div contenteditable="true" id="my-contenteditable-div">
sdfsdfds
</div>
<a href="#" id="getcode" >Get HTML</a>
<div id="show"></div>
and jQuery
$( "#getcode" ).click(function() {
var contents = $('#my-contenteditable-div').html();
$("#show").text(contents);
});
this is my markup, from my sublayout:
<div class="main-nav">
<a id="tabmovies" href="#" class="main-nav-tab active">Movies</a>
<a id="tabtheatres" href="#" class="main-nav-tab">Theatres</a>
</div>
</div>
and this is my .js ... which the alert indicates the click function is working
// Toggle between movies and theatres
$("#tabmovies").click(function () {
alert("you have clicked movies");
$("tabmovies").addClass("active");
$("tabtheatres").removeClass("active");
});
$("#tabtheatres").click(function () {
alert("you have clicked theatres");
$("tabmovies").removeClass("active");
$("tabtheatres").addClass("active");
});
but the class "active" is not being added or removed. Am I missing something?
To select an element by ID in jquery use "#theID" as selector.
Change
$("tabtheatres").addClass("active");
to
$("#tabtheatres").addClass("active");
Try this,
$("#tabmovies").click(function() {
alert("you have clicked movies");
$("#tabmovies").addClass("active");
$("#tabtheatres").removeClass("active");
});
$("#tabtheatres").click(function() {
alert("you have clicked theatres");
$("#tabmovies").removeClass("active");
$("#tabtheatres").addClass("active");
});
You need to add # before the id selector.
FIDDLE DEMO
Change your code as following:
// Toggle between movies and theatres
var $tabmovies = $("#tabmovies"),
$tabtheatres = ("#tabtheatres")
$tabmovies.click(function () {
alert("you have clicked movies");
$tabmovies.addClass("active");
$tabtheatres.removeClass("active");
});
$tabtheatres.click(function () {
alert("you have clicked theatres");
$tabmovies.removeClass("active");
$tabtheatres.addClass("active");
});
DEMO
You are not selecting anything because you should specify selector correctly. In case of id selector use # symbol. For class selector use . Learn about jquery selectors here. And avoid multiple queries in your code. Select once and use reference many time. It will give you performance gain.
i have a piece of code like this.
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
the thing is while clicking on 'click here to display text', it is calling both functions and displaying 'Text' and 'info'. but i dnt want to display 'info' here. i cannot change the html div structure.
how to do that?
It's a little hidden in the docs, but if you look here: http://docs.angularjs.org/api/ng.directive:ngClick
You can see that parameters it mentions an $event object. So your html will become:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
and then your javascript will become:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle: http://jsfiddle.net/rtCP3/32/
Instead calling functions there inline use jquery to solve this issue:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
demo code for e.stopPropagation(): http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});
For native javascript solution you need to pass event as argument to your 2 methods in order to prevent the event from propagating
<div class="box" onclick="displayinfo(event)">
Then change js to:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
DEMO: http://jsfiddle.net/MvgTd/
whatever you are getting.stopPropagation();
in your case
$event.stopPropagation();
I used this tutorial to hid/show DIVs. Unfortunately for some reason it's no longer working (I modified a few things in my code in the meantime)... Do you see where the issue come from? jsfiddle: http://jsfiddle.net/Grek/C8B8g/
I think there's probably a conflict btw the 2 scripts below:
function showonlyone(thechosenone) {
$('.textzone').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
}
else {
$(this).hide(200);
}
});
}
$('.activity-title a').click(function(){
$('.textzone').fadeOut(2000);
var region = $(this).attr('data-region');
$('#' + region).fadeIn(2000);
})
You have a few problems going on. You're missing data-source on your <a> elements. Their "region-source" is hidden inside of the href with some function. I removed that put it into data-source and now it all works fine.
You want to do something like this:
$('.activity-title a').click(function(){
var region = $(this).attr('data-region');
$('.textzone:visible').fadeOut(2000, function () {
$('#' + region).fadeIn(2000);
});
return false; // stops href from happening
});
// HTML Structured like so:
<div class="source-title-box"><span class="activity-title">
Our region</span>
</div>
jsFiddle DEMO
I assume from your markup in the jsFiddle that for every link (.activity-title a), there is a .textzone. I removed the onclick event from these anchors. This way The first link corresponds with the first .textzone:
<div id="source-container">
<div id="source-region" class="textzone">
<p><span class="activity-title">Interacting with the nature</span></p>
<p>blablabla</p>
</div>
<div id="source-oursource" class="textzone">
<p><span class="activity-title">Pure, pristine, and sustainable source</span></p>
<p>blablabla</p>
</div>
<div class="source-title-box"><span class="activity-title">Our region</span></div>
<div class="source-title-box"><span class="activity-title">Our source</span></div>
</div>
Then with the script I simply use the index of the link which is clicked to determine the appropriate .textzone to show:
var textZones = $(".textzone");
var anchors = $('.activity-title a').click(function(e){
e.preventDefault();
var index = anchors.index(this);
textZones.filter(":visible").fadeOut(2000, null, function() {
textZones.eq(index).fadeIn(2000);
});
})
I've got several list items, when I click on the item I want the browser to redirect to ".title > a" link (href). But I don't want any event on the "notThis" selector.
see the example
http://jsfiddle.net/VTGwV/29/
<div class="item">
<div class="title">
jsfiddle.net
</div>
<div> djføljdsaføljdsf a</div>
<div> djføljdsaføljdsf a</div>
<div> djføljdsaføljdsf a</div>
<div class="notThis">
link1
link2
</div>
script
$(document).on('click', '.item', function(event) {
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});
I've tried :not('.notThis') without any luck.
Changes
Thanks for all the answers, but I found another problem. If I have a event handler on the whole item , I can't manage to click on the link in "notThis" selector, because it returns only "false". Isn't there a way to use .not / :not combined with $(document).on('click', -------)
You can test whether the click event originated from within the .notThis element (or the element itself):
$(document).on('click', '.item', function(event) {
if($(event.target).closest('.notThis').length > 0) {
return false; // if you want to ignore the click completely
// return; // else
}
window.location.href = $(event.currentTarget).find('.title > a').attr('href');
});
I also think you can use this instead of event.currentTarget.
Your syntax is wrong, just use the selector like this:
Example
$("div.item > div:not(.notThis)").click(function(){
window.location.href = $(this).find('.title > a').attr('href');
});
http://jsfiddle.net/Lcg49/4/
var clickable = $('.item').find('div').not('.notThis');
$(clickable).on('click', function(event) {
alert($(this).parent().find('.title a').attr('href'));
});