Dynamic Div Content with just clicking one link/button - javascript

I need help here please.
I want to show dynamic content to a div. I already have the code below:
<script type="text/javascript"><!--
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
//--></script>
<div id="example1div" style="padding:10px; text-align:left;">
<p>Content 1</p>
</div>
<p align="center">View another</p>
What it does is, when click the "View another" it replace the 'Content 1' to 'Content 2' but what I want here is that, when 'Content 2' is already shown, I want to click the "View another" link again and replace the div content again with the new content like 'Content 3'.
Anyone please help me solve this.
Thanks in advance :)

Updated after OP's comment
HTML
include jQuery library file
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
Use Plugin https://github.com/fkling/jQuery-Function-Toggle-Plugin --> It accepts an arbitrary number of functions and can be used for any event.
DEMO
You want something like this.
<script type="text/javascript">
/*
* jQuery Function Toggle Pluing
* Copyright 2011, Felix Kling
* Dual licensed under the MIT or GPL Version 2 licenses.
*/
(function ($) {
$.fn.funcToggle = function (type, data) {
var dname = "jqp_eventtoggle_" + type + (new Date()).getTime(),
funcs = Array.prototype.slice.call(arguments, 2),
numFuncs = funcs.length,
empty = function () {},
false_handler = function () {
return false;
};
if (typeof type === "object") {
for (var key in type) {
$.fn.funcToggle.apply(this, [key].concat(type[key]));
}
return this;
}
if ($.isFunction(data) || data === false) {
funcs = [data].concat(funcs);
numFuncs += 1;
data = undefined;
}
funcs = $.map(funcs, function (func) {
if (func === false) {
return false_handler;
}
if (!$.isFunction(func)) {
return empty;
}
return func;
});
this.data(dname, 0);
this.bind(type, data, function (event) {
var data = $(this).data(),
index = data[dname];
funcs[index].call(this, event);
data[dname] = (index + 1) % numFuncs;
});
return this;
};
}(jQuery));
$('#chnage_p').funcToggle('click', function () {
$('#example1div').text('Content 1');
}, function () {
$('#example1div').text('Content 2');
}, function () {
$('#example1div').text('Content 3');
}, function () {
$('#example1div').text('Content 4');
});
</script>

Related

Use cookies to toggle body class

I've being bashing my head around finding a working solution for this.
Goal is to create a text size switcher for people with poor eyesight.
I have created three span elements with classes small, medium and large.
And I have a piece of code that almost gets the job done but it needs that cookie part.
$(function() {
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
return false;
});
});
How can i use cookies to save my selection and add it after page refresh ?
Have been reading many stackoverflow posts about setting cookies but all of them feature only one toggle. Here I have three.
JSFIDDLE HERE
Many thanks!
$(document).ready(function(){
$(".font-toggle span").click(function() {
var size = $(this).attr('class');
$("body").attr("id", size);
if($.cookie('mycookie') == 'valueOfCookie'){
$.cookie('mycookie', '');
}
else{
$.cookie('mycookie', 'valueOfCookie');
}
return false;
});
if($.cookie('mycookie') == 'valueOfCookie'){
$("body").attr("id", 'big-font');
}
else{
$("body").removeAttr("id");
}
});
#big-font{
font-size: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<div class="font-toggle">
<span class="big-font">
Button
</span>
</div>
<div>
Text To Show
</div>
Maybe this will work for you.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").addClass(eyesight);
} else
setEyesight('medium'); // Default size
$(".font-toggle span").click(function() {
setEyesight($(this).attr('class'));
});
});
function setEyesight(size) {
let eyesight = $.cookie('eyesight');
if (eyesight != undefined) {
$("body").removeClass(eyesight);
$.removeCookie('eyesight');
}
$("body").addClass(size);
$.cookie('eyesight', size);
}
</script>
What about this?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/releases/download/v1.4.1/jquery.cookie-1.4.1.min.js"></script>
<script>
"use strict";
$(document).ready(function() {
let eyesight = new Eyesight();
eyesight.initialize();
$(".font-toggle span").click(function() {
eyesight.set($(this).attr('class'));
});
});
function Eyesight() {
let self = this;
let name = "eyesight";
let current = null;
let _default = "medium";
let data = $.cookie(name);
// initialzie
this.initialize = function() {
if (data!= undefined) {
$("body").addClass(data);
current = data;
} else
self.set(_default); // Default size
// init cookie listener
self.listener();
};
// set eyesight function
this.set = function(size) {
if (data != undefined) {
$("body").removeClass(data);
$.removeCookie(name);
}
$("body").addClass(size);
$.cookie(name, size);
current = size;
};
// eyesight cookie listener function
this.listener = function() {
setTimeout(function() {
let cookie = $.cookie(name);
if (cookie != undefined && cookie != current)
self.set(cookie);
self.listener();
}, 100);
};
}
</script>

Stop incremental counter and disable interaction

I am trying to get the counter to stop at 0 and when it does the entire div is unclickable/disable interaction.
There is a link in the middle. So when i click 3 times I want it to be un-clickable.
edit:also it doesn't need to use Knockout. any approach, if more simple is fine.
What would be the best approach?
Fiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
Simply try adding this line
if (this.numberOfClicks() > 0)
Before
this.numberOfClicks(this.numberOfClicks() - 1);
We'll get something like that:
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(3);
this.registerClick = function() {
if (this.numberOfClicks() > 0)
this.numberOfClicks(this.numberOfClicks() - 1);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() <= 0;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
See Fiddle
A bit late but give a look to my solution because I simplified a lot your code and I think you can get some value from it (for example the use of var self = this which is a best practice).
The idea behind my solution is very simple:
1) Show or hide the link or a normal text with respect to your hasClickedTooManyTimes computed variable.
empty link
<p data-bind='if: hasClickedTooManyTimes'>empty link</p>
2) Simply block the click on div if hasClickedTooManyTimes is true.
self.registerClick = function() {
if(!self.hasClickedTooManyTimes()){
self.numberOfClicks(this.numberOfClicks() - 1);
}
};
Check the Fiddle!
Let me know if this was useful to you!
Just disable the link when your count is done:
First add an id to your link:
<a id="a1" href=#> <p>empty link</p> </a>
Next disable that id when the time is right like this in your javascript:
this.hasClickedTooManyTimes = ko.computed(function() {
if (this.numberOfClicks() < 0) {
$('#a1').attr('disabled', 'disabled'); // <--- disable it
}
return this.numberOfClicks() <= 0;
}, this);
Take a look at the fiddle for JS code, stackoverflow is not validating my code section for the JS content.
HTML
<body>
<div>You have teste clicks!</div>
<div id="demo"></div>
</body>
JS
var btnObserver = (function() {
var me= this;
var clickleft = 3;
var registerClick = function() {
if(clickleft > 0) {
clickleft--;
}
};
var isCLickable = function() {
console.log(clickleft);
return clickleft !== 0;
};
return {
registerClick: registerClick,
isCLickable: isCLickable
}
})();
document.getElementById("mybtn").addEventListener("click", function(){
var message= "Hello World";
btnObserver.registerClick();
if(!btnObserver.isCLickable()) {
message= "X Blocked!";
// return false or do anything you need here
}
document.getElementById("demo").innerHTML = message;
});
Fiddle: http://jsfiddle.net/qkafjmdp/

How do I make tinyMCE editor stay in my jQgrid textarea formedit form after first initialize?

I have a jqgrid that I am trying to use tinyMCE in the text area to send/store html in my database and reload to my grid. I have a custom column with tinyMCE for the text area but after I open editform once and close it next time it is opened tinymce does not initialize and a regular textarea appears. (Also when url modal it looses focus and focuses on editform. The text is pasted to the back "Project" field instead(picture below).)What I'm I doing wrong?
Reason why my TineMCE "Links" was losing focus was because of a simple syntax error. I had modal:true in the editgrid code.
UPDATE FOR WORKING INLINE EDIT IMPLEMENTATION
Here are examples for correct implementation for inline edit(Thank you #Oleg): DEMO1 | DEMO2
INLINE EDIT WORKING CODE SAMPLE:
{ name: "note", width: 260, sortable: false, editable: true,
//edittype: "textarea"
edittype:'custom',
editoptions: {
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
},
custom_value: function (element, oper, gridval) {
var id;
if (element.length > 0) {
id = element.attr("id");
} else if (typeof element.selector === "string") {
var sels = element.selector.split(" "),
idSel = sels[sels.length - 1];
if (idSel.charAt(0) === "#") {
id = idSel.substring(1);
} else {
return "";
}
}
if (oper === "get") {
return tinymce.get(id).getContent({format: "row"});
} else if (oper === "set") {
if (tinymce.get(id)) {
tinymce.get(id).setContent(gridval);
}
}
}}
}
jqGrid column:
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
<script src="tinymce/tinymce.min.js"type="text/javascript"></script>
<script src="tinymce/jquery.tinymce.min.js"type="text/javascript"></script>
<script src= "tinymce/plugins/link/plugin.min.js" type="text/javascript"></script>
<script type="text/javascript">
...
{ name:'notes',
index:'notes',
edittype:'custom', editable:true,
editoptions:{
"custom_element":function( value , options) {
var elm = $('<textarea></textarea>');
elm.val( value );
// give the editor time to initialize
setTimeout( function() {
tinymce.init({selector: "textarea#notes",plugins: "link"});
}, 100);
return elm;
},
"custom_value":function( element, oper, gridval) {
if(oper === 'get') {
return tinymce.get('notes').getContent({format: 'row'});
} else if( oper === 'set') {
if(tinymce.get('notes')) {
tinymce.get('notes').setContent( gridval );
}
}
}}}
Try to replace the code of custom_element to the following
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
}
One more simpel

How to do queue of messages that shows in one div after delay?

How to implement queue which elements after shown with delay fadeOut and split out from array? This funcionallity should be provide message shows one after another in the same div even when showAlertBarMessages() is invoked many diffrent times like in FIFO. For now I can't clean shown elements. I spend one day and I don't know.
My current solution and working example: http://jsfiddle.net/ZtY38/:
var msgQueue = [];
var i = 1;
$('#add-msg').click(function () {
msgQueue.push("Message number " + i);
showAlertBarMessages();
i++;
});
function showAlertBarMessages() {
msgQueue.map(function (msg, idx) {
return function () {
var el = $('<div />').html(msg).addClass('msg').insertBefore('#msg-sequentially');
$(el).click(function () {
console.log("fadeOut and remove from queue");
});
if (idx > 0) {
return el.delay(2000).fadeIn(500).promise()
} else {
return el.fadeIn(500).promise()
}
};
}).reduce(function (cur, next) {
console.log("alredy shown fadeOut and remove from queue");
return cur.then(next);
}, $().promise());
}
HTML:
<div id="msg-sequentially"></div>
<button id="add-msg">Add next message</button>
Instead insertBefore should be append to #msg-sequentially but this doesn't work.
Or is there any completely other approach for this solution?
You could try that and see if it's fitting your needs:
DEMO
function showAlertBarMessages() {
var msg = msgQueue[0];
if (!$('#msg-sequentially').find(':visible').length) {
var el = $('<div />').html(msg).addClass('msg').appendTo('#msg-sequentially');
el.fadeIn(500).promise().done(function () {
$(this).delay(2000).fadeOut().promise().done(function () {
$(this).remove();
msgQueue.splice(0,1);
if(msgQueue.length) showAlertBarMessages();
});
});
}
}

Prompt popup in bootbox is not closing

The prompt popup that occurs when I click the button with class 'alert3' does not close.
CLICKMEMEMEMEMEME
and this is the function that I am invoking:
<script>
$(document).on("click", ".alert3", function(e) {
bootbox.prompt("What is your name?", function(result) {
if (result === null) {
Example.show("Prompt dismissed");
} else {
Example.show("Hi <b>"+result+"</b>");
}
});
});
</script>
The popup does not close because you have an error in the callback function, so it crashes before bootbox can make the popup disappear.
The best guess is that Example is not defined in your code. Maybe you took it on the Bootbox website, they are using a javascript object called Example.
If you want to show the result with your callback function, you can add this to your html:
CLICKMEMEMEMEMEME<br/>
<p id='result'></p>
And then change your javascript:
<script>
$(document).on("click", ".alert3", function(e) {
bootbox.prompt("What is your name?", function(result) {
if (result === null) {
$('#result').html("Prompt dismissed");
} else {
$('#result').html("Hi <b>"+result+"</b>");
}
});
});
</script>
Prompt popup in bootbox.js
That is not working because Example function is not defined there.We need to first defined them that using current selector value and text associated with them.here $("#result") is used to show error message in particular div.
html code:
<p>Click here-><a class="alert" href=#>Alert!</a></p><p id='result'</p>
code:
var Example = (
function()
{
"use strict";
var elem,
hideHandler,
that = {};
that.init = function(options) {
elem = $(options.selector);
};
that.show = function(text) {
clearTimeout(hideHandler);
$("#result").html(text);
$("#result").fadeIn();
hideHandler = setTimeout(function() {
that.hide();
}, 4000);
};
that.hide = function() {
$("#result").fadeOut();
};
return that;
}());

Categories

Resources