简体   繁体   中英

JS insert URL link from textarea to the image src with live preview

How can I insert URL text from textarea to the image src with this code:

 var wpcomment = document.getElementById('previewimage'); wpcomment.onmouseover = wpcomment.onkeyup = wpcomment.onkeypress = function(){ document.getElementById('prevCom').innerHTML = this.value; }
 <textarea name="previewimage" id="previewimage" placeholder="drag drop here"></textarea> <div id="prevCom"><img alt="" id="nahled" src=""></div>

I already asked here: jQuery: how turn link from textarea to image in div?

but there is only jQuery solution with no live preview.

I think there is no need to capture keypress and mouse leave. besides by changing image attribute like below, or image.setAttribute('src', this.value)

 var wpcomment = document.getElementById('previewimage'); var image = document.getElementById('nahled'); wpcomment.onkeyup = function(){ image.src = this.value; }
 <textarea name="previewimage" id="previewimage" placeholder="drag drop here"></textarea> <div id="prevCom"> <img alt="" id="nahled" src="" /> </div>

 var wpcomment = document.getElementById('previewimage'); wpcomment.onmouseover = wpcomment.onkeyup = wpcomment.onkeypress = function(){ document.getElementById('nahled').src = this.value; }
 <textarea name="previewimage" id="previewimage" placeholder="drag drop here"></textarea> <div id="prevCom"><img alt="" id="nahled" src=""></div>

Here is a version with test and eventListener

 const wpcomment = document.getElementById('previewimage'); const image = document.getElementById('nahled'); wpcomment.addEventListener("input", function() { const str = this.value.trim(); if (str.startsWith("data:")) { // data uri image.src=str; return; } try { const url = new URL(str); // if (url.href.contains(....) ===-1) { /* test extension here */ } image.src=url.href; } catch (_) { console.log("Not a valid URL") return false; } });
 #prevCom img { height: 300px; } #prevCom img::before { content: "ッ"; }
 <textarea name="previewimage" id="previewimage" placeholder="drag drop here"></textarea> <div id="prevCom"> <img alt="" id="nahled" src="" /> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM